Safely Restarting a Scene

I’ve learned that when restarting a scene you need to be sure to remove any event listeners so they don’t double up. What are other things you need to look out for when restarting a scene? What is the right way to make sure all your cleanup happens? I use a custom “restart” function that I call before actually restarting the scene.

create(){
     this.events.on('test', this.testEvent, this);
}

myCustomRestartFunction(){
    this.events.off('test', this.testEvent);
    this.scene.restart();
}

testEvent(){
     console.log('hello');
}

You can do this in a scene shutdown event handler (!) added with once(). That way it’s impossible to skip cleanup.

Thanks! I want to make sure I’m doing this the right way. It seems that if you add a scene shutdown event handler you also need to make sure you turn it off at shutdown.

create(){
        this.events.on('shutdown', this.shutDownListener);
        this.events.on('somOtherEvent', this.checkEnemies, this);
}

shutDownListener(){
    this.events.off('shutdown', this.shutDownListener);
    this.events.off('somOtherEvent', this.checkEnemies, this);
    console.log("SHUTDOWN");
}

You can do it that way or with once():

this.events.once('shutdown', this.shutDownListener);

Then there’s no need to do off('shutdown', …).

I’m not doing it right.

create(){
    this.events.once('shutdown', this.shutDownListener);
    this.events.on('someOtherEvent', this.checkEnemies, this);
}

shutDownListener(){
    this.events.off('someOtherEvent', this.checkEnemies);
}

TypeError: undefined is not an object (evaluating ‘this.events.off’)

this.events.once('shutdown', this.shutDownListener, this);

That worked. Marked as solution :slight_smile: