This.scene is undefined

Hey.

I’m currently working on a small game, and recently I’ve been trying to incorporate scenes into my game so I can have a new scene after the player completes the level. However, every time I try to invoke this.scene.start('EndScene');, it returns TypeError: this.scene is undefined.

Here is a snippet of my code:

function playerCollideEnd(){
      console.log('ya made it');
      this.scene.start('EndScene');      
    }

In fact, any time I try to invoke this.scene.get('GameScene');, or any similar function in my GameScene, it will return the undefined error. Please let me know if you want to see anymore code.

Thanks.

What is the context inside of playerCollideEnd()?

function playerCollideEnd() { 
  console.log(this); 
}

Thanks for replying.

console.log(this); will log function playerCollideEnd() to the console. The function itself is called when the player collides with the end marker. This is all located within class GameScene extends Phaser.Scene under the create() function.

console.log(this); outside of any functions but still within create() logs Object { sys: {…}, game: {…}, anims: {…}, cache: {…}, plugins: {…}, registry: {…}, scale: {…}, sound: {…}, textures: {…}, facebook: {…}, … }.

So, you somehow have to pass a reference to the scene inside playerCollideEnd() .
Maybe with an arrow function?

const playerCollideEnd = () => { 
  console.log(this); // this will be the scene
  console.log('ya made it'); 
  this.scene.start('EndScene'); 
}

Also, have you added the proper “key” into super()?

class EndScene extends Phaser.Scene {
  constructor() {
    super({ key: 'EndScene' })
  }
}

Okay, that makes sense. I tried using the arrow function but then unfortunately the playerCollideEnd() didn’t function as a callback for a collider. However! I just made an arrow function that playerCollideEnd() calls upon and it works! Thanks so much.

Here’s what I fully did:

function playerCollideEnd() { 
  console.log('ya made it'); 
  endFunc(); //not a good name i know
}
const endFunc = () => {
      this.scene.start('EndScene'); 
}

Thank you so much!

1 Like

I highly suggest you read a bit more about JavaScript’s scope and closures and what ‘this’ represents in each context (maybe something like https://javascriptplayground.com/javascript-variable-scope-this/ or https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback). It will help you a lot in the future when you face this kind of issue.

1 Like

I have the same problem, but I can’t figure out how to solve it.

class title extends Phaser.Scene {
constructor() {
super({key: ‘title’});
}
preload() {
var socket = io();
}
create() {
socket.on(‘acceptedplayer’, function() {
this.scene.start(“main”);
});
}
}