I need to switch between two scenes in my Phaser3 (version 3.21.0) app without any side effects. The first scene handles the menu with high score, while the second scene is for the actual gameplay.
Code snippets:
The app.ts
file is as follows:
const config = {
title: '<game-name>',
width: 800,
height: 600,
parent: 'game',
scene: [MenuScene, GameScene],
};
export class GameName extends Phaser.Game {
constructor(config: any) {
super(config);
}
}
window.onload = () => new GameName(config);
The MenuScene.ts
- relevant part shown below:
class MenuScene extends Phaser.Scene {
constructor() { super({key: 'MenuScene'}); }
create():void {
console.log('create menuscreen');
const enter = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.ENTER);
enter.on('down', () => { this.scene.start('GameScene'); }
}
}
The GameScene.ts
- relevant code excerpt provided:
class GameScene extends Phaser.Scene {
constructor() { super({key: 'GameScene'}); }
create = ():void => {
console.log('create gamescreen');
const esc = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.ESC);
esc.on('down', () => { this.scene.start('MenuScene'); }
}
}
Issue and question:
When I repeatedly press Enter and Esc to switch between scenes using the provided solution, it doesn't seem to clean up the background scenes. After switching a few times, the console displays errors like in the image below after 6 switches: https://i.sstatic.net/5cp3P.png
I have tried calling this.scene.stop()
before
this.scene.start('<scene-key>')
, but the issue persists. I also checked similar questions on Phaser3 Scenes transitions but couldn't find a solution. It was mentioned that the start()
method should clean up or shut down the unused scenes.
How can I properly switch between scenes or clean up the currently unused scene?
Thank you!