Phaser 3.16.2: Main scene duplicates on scene.restart()

Hi,

I’m pretty new to Phaser 3, but I’m having an interesting problem. When my ship is destroyed, I call this.scene.restart() but it keeps duplicating the scene and causing the game objects to keep doubling. Looks pretty cool when objects blow up, but would like some advice on how to fix it.

gameScene.create=function()
{
console.log(">> Manager: "+this.scene.manager._queue.length);

Thanks,
–DaSoup

This could happen by calling scene.restart() several times during the same step, or for some other reasons. Could you post code for the whole scene, if not too big?

Hi Samme,

Let me see what I can pull together.

It’s pretty cool. It’s like layers of the same scene and they are all playing. So each restart causes the others to restart and create more scenes. 2, 4, 8, 16, etc.

Are you using scene events?

Hi Samme,

Sorry for the delay and thanks for the help. Yes I am using an event, snippet below, is that bad?

Thanks,
–DaSoup

destroyed(ship) {
    console.log("ship destroyed...");
    ship.scene.events.emit('game_over', ship);
}

this.events.on('game_over', (ship)=> {
    ship.visible=false;
    ship.setVelocity(0);
    this.playerExplodes(ship);
    ship.active=false;
    ship.disableBody();
    this.cameras.main.shake(100);
    this.sndAstExplode.play();
    this.playerAlive=false;

    obj.timeEvent=this.time.addEvent({
        delay: 3000,
        callback: () => {
            console.log("restart scene.");
            this.scene.restart();
        }
    });
});

It’s not bad, just tricky, because scene event handlers aren’t removed when the scene is stopped or restarted. So you have to be careful not to add duplicate handlers.

  • If you’re using a scene class, add event handlers in the scene’s constructor.

  • Otherwise, if an event handler needs to run only once per scene start–stop, add it with once() instead of on(). That might suit your game_over event.

  • Otherwise, remove any event handlers when stopping or (re)starting the scene. You can do this from a shutdown event or even right before adding any handlers, e.g.,

    function create () {
      this.events.off('game_over');
      this.events.on('game_over', /* etc. */);
    }
    
5 Likes

Thanks Samme. Will try to reorganize things. I looked back at some of the Zenva tutorials, RPG, and he passes a flag to the restart event to avoid reloading things.

DaSoup