Scenes
How Scenes start and stop, how to run several at once, pass data between them, and clean up when one shuts down.
Source: src/scene/ScenePlugin.js (this.scene), src/scene/SceneManager.js, src/scene/Systems.js (this.sys), src/scene/Settings.js, src/scene/typedefs/SettingsConfig.js, src/scene/events/. Related: phaser4-core, game-setup-and-config, events-system, data-manager, loading-assets.
Quick start
class Level extends Phaser.Scene
{
constructor ()
{
super('Level');
}
init (data)
{
// Runs on every start and restart. Reset state here, not in the constructor
this.level = data.level ?? 1;
this.lives = 3;
}
preload ()
{
this.load.image('player', 'assets/player.png');
}
create ()
{
this.player = this.add.image(this.scale.width / 2, this.scale.height / 2, 'player');
this.input.keyboard.once(Phaser.Input.Keyboard.Events.KEY_DOWN + 'N', () =>
{
this.scene.restart({ level: this.level + 1 });
});
}
update (time, delta)
{
this.player.rotation += 0.001 * delta;
}
}
new Phaser.Game({ width: 1024, height: 768, scene: [ Level ] });
Lifecycle
constructorruns once, when the Scene is added.init(data)runs on every start.STARTandREADYare emitted onthis.eventsjust before it.preload(), then the Loader runs. Files in the Scene config'spackare loaded beforepreload.create(data), after loading. With nopreload, it runs straight afterinit.CREATEis emitted after it.update(time, delta)every frame while the Scene is running.
The status is this.sys.getStatus(): Phaser.Scenes.PENDING (0), INIT, START, LOADING, CREATING, RUNNING (5), PAUSED, SLEEPING, SHUTDOWN, DESTROYED (9).
The Scenes in the game config start when the game emits READY, after the global plugins are installed, and before callbacks.postBoot runs. Since 4.3, that holds for every renderer, including HEADLESS and jsdom tests (#7348). The full boot order is in game-setup-and-config.
Scene config
Pass it to super(), or as the Scene's entry in the game config.
constructor ()
{
super({
key: 'Level',
active: false, // true starts it at boot. The first Scene in the game config always starts
physics: { arcade: { gravity: { y: 300 } } }, // turns on physics for this Scene, even with no game default
loader: { path: 'assets/level/' },
pack: { files: [ { type: 'image', key: 'bar', url: 'bar.png' } ] },
plugins: [ 'Loader', 'TweenManager' ] // only these Scene plugins. Leave out for all of them
});
}
pluginslists the Scene plugins to install:'Clock','DataManagerPlugin','InputPlugin','Loader','TweenManager','LightsPlugin', plus any from the game config. With[],this.time,this.data,this.input,this.load,this.tweensandthis.lightsare all undefined.this.add,this.cameras,this.eventsandthis.sceneare always there.mapreplaces the whole injection map, so every property you leave out, such asthis.addorthis.cameras, is no longer set.mapAddadds properties to the map, but can't rename ones it already has.- A Scene can be an object:
{ key: 'Menu', create () {}, update () {}, extend: { helper () {} } }. The functions inextendbecome Scene properties. - In TypeScript,
this.scene.get<UI>('UI')returns the Scene typed as your class.
Moving between Scenes
| Method | What it does |
|---|---|
start(key, data) |
Stops this Scene and starts key. With no key, restarts this Scene |
restart(data) |
Stops this Scene and starts it again |
launch(key, data) |
Starts key alongside this Scene |
run(key, data) |
Wakes key if it's asleep, resumes it if it's paused, otherwise starts it |
pause(key, data), resume(key, data) |
A paused Scene doesn't update, and takes no input, but it still renders |
sleep(key, data), wake(key, data) |
A sleeping Scene doesn't update or render, and keeps its state |
switch(key, data) |
Sleeps this Scene. Wakes key if it's asleep, otherwise starts it |
stop(key, data) |
Shuts key down. Its Game Objects are destroyed |
- Each
keydefaults to this Scene. These methods are queued, and run at the start of the next game step, so the other Scene isn't running on the next line. - Starting a Scene which is already running, paused or asleep restarts it. That includes
launchorrunon a running Scene, andswitchto a paused Scene. Checkthis.scene.isActive(key)first if the Scene may already be running. - These run at once:
get,getStatus,isActive,isPaused,isSleeping,isVisible,setActive,setVisibleandtransition. - The render-order methods, and
addandremove, run at once, or at the next step if called while the Scenes are updating:bringToTop,sendToBack,moveUp,moveDown,moveAbove(keyA, keyB),moveBelow(keyA, keyB),swapPosition. this.scene.add(key, SceneClass, autoStart, data)adds a Scene at run time.remove(key)destroys it.
Passing data
start,restart,launchandrunpassdatatoinit(data)andcreate(data).this.sys.getData()returns it later.restart()with no data, orstart(key)with none, reuses the data from the last start. Pass{}to clear it.- Data given to
pause,resume,sleep,wake, and to aswitchorrunwhich wakes or resumes a Scene, reaches only that event's listeners, as(sys, data).initandcreatedon't run again.
create ()
{
const onWake = (sys, data) =>
{
this.lives = data?.lives ?? this.lives;
};
this.events.on(Phaser.Scenes.Events.WAKE, onWake);
// this.events lives as long as the Scene, so remove the listener or it is added again on restart
this.events.once(Phaser.Scenes.Events.SHUTDOWN, () =>
{
this.events.off(Phaser.Scenes.Events.WAKE, onWake);
});
}
- For state which many Scenes share, use
this.registry(one for the game).this.databelongs to the Scene, and keeps its values across a restart until you callthis.data.reset(). See data-manager.
Running Scenes together
- Scenes render in the order of the game config's
scenearray, so later ones are drawn on top. The top Scene updates first, and gets input first. - A HUD is a second Scene, listed after the game Scene in the config (or moved with
bringToTop), and launched by it. It has its own Camera, so it doesn't scroll or zoom with the game. - To pause the game under a menu:
this.scene.pause()thenthis.scene.launch('Pause'). The paused Scene takes no input, so the Pause Scene must handle the resume:this.scene.resume('Level')thenthis.scene.stop().
One Scene listening to another must remove its listener when it shuts down, because the other Scene's emitter outlives it:
// In the Level Scene, when a coin is collected
this.events.emit('score', 10);
// In the HUD Scene
create ()
{
const text = this.add.text(16, 16, 'Score: 0');
const level = this.scene.get('Level');
let score = 0;
const onScore = (points) =>
{
score += points;
text.setText(`Score: ${score}`);
};
level.events.on('score', onScore);
this.events.once(Phaser.Scenes.Events.SHUTDOWN, () =>
{
level.events.off('score', onScore);
});
}
The registry works the same way. Its change event for one key is Phaser.Data.Events.CHANGE_DATA_KEY + 'score', with (parent, value, previousValue), on this.registry.events. Remove it on SHUTDOWN too.
Cleaning up
A Scene instance is kept when it stops, and reused when it starts again. Shutdown destroys its Game Objects, tweens, timers, physics world, Key objects and this.input listeners. It doesn't remove:
- listeners on
this.events, the Scene's own emitter, which lives as long as the Scene. One added increateis added again on every restart; - listeners on anything global:
this.registry,this.scale,this.game.events,this.sound,this.textures, or another Scene'sevents; - sounds made with
this.sound.add, which belong to the game; - key captures, which are global. See input-keyboard-mouse-touch.
Remove these on SHUTDOWN, which runs on every stop and restart. DESTROY runs only when the Scene is removed from the game.
create ()
{
const tick = (time, delta) => { /* every frame */ };
this.events.on(Phaser.Scenes.Events.UPDATE, tick);
this.events.once(Phaser.Scenes.Events.SHUTDOWN, () =>
{
this.events.off(Phaser.Scenes.Events.UPDATE, tick);
});
}
Transitions
transition() runs both Scenes for duration ms, then stops (or sleeps) this one. It draws nothing itself: fade the Cameras yourself.
// In the Scene going out
if (this.scene.transition({ target: 'Level2', duration: 500, data: { level: 2 } }))
{
this.cameras.main.fadeOut(500);
}
// In Level2's create
this.cameras.main.fadeIn(500);
- It returns
false, and does nothing, if the target doesn't exist, is already running, or either Scene is already transitioning. - Keys:
target,duration(1000),sleep(false: stop this Scene at the end),remove,allowInput(false),moveAbove,moveBelow,data,onUpdate(progress),onStart. - Events:
TRANSITION_OUT (targetScene, duration)on this Scene. On the target:TRANSITION_INIT(afterinit), thenTRANSITION_START(aftercreate) orTRANSITION_WAKE, each with(fromScene, duration), andTRANSITION_COMPLETE (fromScene)at the end.
Gotchas
- Listeners on
this.eventsadded increatepile up across restarts, as do those on global emitters. Remove them onSHUTDOWN. this.scene.start('X')stops the current Scene. Uselaunchto keep both.launch,runorstarton a running Scene restarts it.- Scene methods are queued until the next step.
- Data given to
wakeorresumeonly reaches the event, notinitorcreate. restart()with no data reuses the old data.- Set up per-run state in
init, not the constructor, which runs once. this.physicsandthis.matterexist only if the game or the Scene config sets up that physics.- Never overwrite
this.sys.
