Error referencing "this" in update when switching scenes

Hi Everyone! Just wondering if this a Phaser bug or if I’m doing something really wrong:

  1. I load Scene A with start - works fine.
  2. I load Scene B with start - works fine.
  3. I load scene A again with start and I get this error generated from the update method of Scene B:
SceneA.js?8e01:658 Uncaught TypeError: Cannot read property 'position' of undefined

(the position property is from this.player.body.position that was created in Scene A’s create. Method.)

It seems if after I request to change scenes using start, the previous scene’t update method still runs, but it can’t find this.player.body.position (… because it’s apparently been already destroyed?)

Note that both scenes have objects called this.player.body.position, I’m switching scenes using this format currentScene.start("NextScene") and I only get this error if start a scene that’s previously been loaded using start.

Has anyone encountered something similar?

Hi @kittykatattack,
Maybe this problem could be related to this issue:

It’s not related. I think it’s actually caused by another bug which will be fixed in 3.50. Essentially, the first time a scene starts, it will only run its update method after create has run. However, if the scene is shut down and started again, it will always run its update method, even during preload.

Assuming that this behavior is the cause of your problem, you can work around it by putting the following at the top of your update method:

if(this.sys.settings.status < Phaser.Scenes.RUNNING){
    return;
}
1 Like

@Telinc1 Thank you so much!! You confirmed what I suspected and that it’s probably a Phaser bug! I will attempt your fix and report back :slight_smile:

This one?

Yeah, I might have the wrong issue. I was thinking of this one. I’m not sure which exact issue causes the error in this case, or if it even is a Phaser bug.

If this is related to the preload/update issue.You can also try to preload all you asstes in a spearate scene (e.g. a loding screen) which actually gets only called once at startup of your game.

Hi Everyone! Just revisiting this and wanted to let you know none of the above suggested fixes worked. I’m currently hacking around this by wrapping all my update code inside and if statement the checks for the existence of player.scene

update() {
  if (this.player?.scene !== undefined) {
   //all scene update code here
  }
}

… still no idea what’s going on, but if I figure it out I’ll let you all know :slight_smile:

(PS: I’m on 3.50.1)