TypeError this.scene is undefined

class title extends Phaser.Scene {
constructor() {
super({key: ‘title’});
}
preload() {
var socket = io();
this.load.atlas(“sprites”, “client/img/spritesheet.png”, “client/img/sprites.json”);
this.load.atlas(“explosion”, “client/img/explosionspritesheet.png”, “client/img/explosionsprites.json”);
}
create() {
this.add.image(0, 0, ‘sprites’, “sky”).setOrigin(0, 0);
this.add.image(100, 150, ‘sprites’, “Spaceship1”).rotation = 14.6;
this.add.image(200, 200, ‘sprites’, “Bullet1”).rotation = 14.6;
this.add.image(300, 250, ‘sprites’, “Bullet1”).rotation = 14.6;
this.add.image(400, 300, ‘sprites’, “Bullet1”).rotation = 14.6;
this.add.image(500, 350, ‘explosion’, “explosion5”).rotation = 14.6;

socket.on('acceptedplayer', function() {
  this.scene.start("main");
});

}
update() {
}
}

You should pass the context you want Phaser to use for your event handler. this is one of the more difficult topics in JS for developers to get used to. Basically this is the object before the . (dot) when calling a function. Since you’re handing your function off this isn’t want you expect it to be. You can specify the value of this in your event handler function by passing a third parameter to on (see EventEmitter docs)

https://photonstorm.github.io/phaser3-docs/Phaser.Events.EventEmitter.html#on

To get more comfortable with JavaScript’s `this’ I recommend

https://www.w3schools.com/js/js_this.asp

1 Like

Note, if you do specify the this to be your external this, you’ll likely have to remove .scene as it should be your scene.

Thanks, that worked for me.