Skip to content

Switching scenes

Updated

Scripts change which scenes are shown with the Scenes global: they replace the current level with the next one, add a HUD on top, or take an overlay away. This page covers every method of Scenes, what happens to a script whose own scene goes away, and how to keep a player, music or a score keeper across a switch with Don’t Unload.

  • Scenes explains base, additive and ruling scenes, and why a scene starts as saved each time it loads.
  • Scenes.load returns a promise. To wait for it, the calling function must be async; see Lifecycle hooks.
await Scenes.load('level-2'); // replace the active scenes
await Scenes.load('hud', { additive: true }); // add on top
await Scenes.unload('hud'); // take it away and free it
Scenes.list(); // [{ id, name }] of every scene
Scenes.active(); // ids of the active scenes, base first
Scenes.find('hud'); // a loaded scene, by name or id

The strings in these lines are scene ids. Scenes.list() gives each scene’s id with its name.

Method Returns What it does
load(id, options?) Promise<void> Load the scene and make it active. Resolves once it is shown.
unload(id) Promise<void> Take the scene out of the active set and free it.
list() { id, name }[] Every scene of the project, as a new array.
active() string[] The ids of the active scenes, base first, as a new array.
find(nameOrId) a scene or undefined A loaded scene, by name or id.

load takes these options:

Option Type Default What it does
additive boolean false Add the scene on top of the active ones instead of replacing them.
onProgress (loaded, total) => void none Called as the scene’s assets load, for a progress bar.

The rules:

  • load(id) replaces. Only that scene stays active, even when it was already one of them.
  • load(id, { additive: true }) adds. Loading a scene that is already active, additively, does nothing.
  • Ids only. load and unload throw for an id that is not in list(). Use the ids list() gives, not the names.
  • Leaving frees. A scene that leaves the active set is freed: its entities are disposed, and their scripts stop. Loading it again builds it fresh, as saved.
  • Play only. In editor code, load and unload throw, because they would change the scene being edited. list, active and find work everywhere.

A script can switch away from, or unload, the scene it is in. The runtime makes that safe:

  • The switch starts once the calling function has returned or reached an await, so the function is never cut off halfway.
  • The script’s dispose hook then runs as usual, and its listeners, timers and tweens are released.
  • The promise it awaits never settles, so nothing after the await runs against a scene that is gone.
  • Loading that scene again starts its scripts afresh, from startup.
LevelExit.jx
#pragma lifecycle(startup)
function startup() {
on('level/complete', async () => {
log('Loading the next level');
await Scenes.load('level-2');
log('Never printed: this script left with its scene');
});
}

To run code after the switch, put it in a script that survives the switch (a Don’t Unload entity, below), or in a script of the new scene.

An entity marked Don’t Unload survives a switch with everything under it: a player, background music, a score keeper. There are two ways to mark one, with the same effect:

  • From its script, with #pragma dont_unload(). Write it with its parentheses; it takes no arguments.
  • Without code, with a Don’t Unload component (comp-dont-unload, class DontUnloadComponent). It has no props.

entity.dontUnload tells whether an entity is marked.

When its scene is replaced or unloaded, the marked entity moves to the scene that stays (the one just loaded, or the newest that remains) as a direct child of that scene’s root:

  • It keeps its pose relative to the scene root, however deep it was nested. Its old parent is not kept.
  • Nothing restarts. startup does not run again and dispose does not run. Its own await Scenes.load(…) resolves.
  • scene then refers to the new scene, and findEntity, spawn and destroy work there.
  • It is never copied. When the scene it came from loads again, that scene’s saved copy of the entity is left out, so there is only ever one.
Rule What it means
Play only In the editor, switching scenes moves nothing.
Only unloading moves it An additive load removes no scene, so the entity stays where it is. destroy(entity) still destroys it.
No scene stays When the last scene unloads, the entity goes with it.
Nested A Don’t Unload entity inside another one is not pulled out: it travels inside it.
Each mark on its own Switching the component off unmarks the entity, unless its script also declares the pragma, and the other way round.
Timing The component marks the entity at once. The pragma takes effect once the script has loaded: an entity whose script is still loading stays behind.
Stays behind A scene’s root entity, or an entity whose id the new scene already has, stays behind with a warning in the script log.
Cameras A carried camera is an ordinary camera in the new scene: that scene’s own main camera renders.
Networked entities An entity shared in a multiplayer room moves only when its ownership is locked and this visitor owns it, such as the visitor’s own avatar. See Multiplayer.

#pragma dont_unload() is not allowed in an #editor_only script, which never runs in play.

Survives Does not survive
Don’t Unload entities, their subtrees and their running scripts Every other entity of the scene that left
Singleton instances Scripts’ variables, timers and listeners in that scene
Exports of scripts that are carried along Exports of scripts that unloaded
Data saved with persistence (Multiplayer) Changes made to the scene while it played

Clicking a portal loads the next level. The portal has a Selectable and a Signal Emitter on portal/clicked; the target slot holds the next scene’s name.

Portal.jx
#pragma slot(ref=target, type=String, default="level-2")
#pragma lifecycle(startup)
let targetId;
let leaving = false;
function onPortal(event) {
if (event.eventType !== EventType.Selectable.Select || leaving) return;
findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again
leaving = true;
log('Travelling to', target);
Scenes.load(targetId);
}
function startup() {
const entry = Scenes.list().find((s) => s.name === target);
if (!entry) {
log('No scene named', target);
return;
}
targetId = entry.id;
on('portal/clicked', onPortal);
}

How it works:

  • The target slot lets each portal in the editor point to a different scene, by name.
  • startup turns the name into an id once, with Scenes.list(), and stops early when the scene does not exist.
  • The leaving flag ignores further clicks while the next scene loads.
  • This script is in the scene being replaced, so it stops with it; it does not need to await the load.

Pressing H adds a HUD scene on top of the level, and pressing it again takes it away.

HudToggle.jx
#pragma lifecycle(startup, update)
let hudId;
let busy = false;
async function toggleHud() {
busy = true;
try {
if (Scenes.active().includes(hudId)) await Scenes.unload(hudId);
else await Scenes.load(hudId, { additive: true });
} catch (error) {
log('HUD switch failed:', error.message);
}
busy = false;
}
function startup() {
const entry = Scenes.list().find((s) => s.name === 'hud');
hudId = entry ? entry.id : undefined;
if (!hudId) log('No scene named hud');
}
function update() {
if (!hudId || busy) return;
if (Input.keyboard.isKeyReleased(Key.H)) toggleHud();
}

How it works:

  • additive: true keeps the level and adds the HUD on top. The HUD becomes the ruling scene.
  • Scenes.active().includes(hudId) tells whether the HUD is shown, so one key both opens and closes it.
  • unload frees the HUD; showing it again builds it fresh.
  • The busy flag ignores key presses while a load or unload is in progress, and try/catch reports a failure instead of stopping the script.

A Don’t Unload loading screen shows progress while the next level loads. The Behavior is under an entity marked Don’t Unload that also holds a UI Label named Loading Text.

Loader.jx
#pragma dont_unload()
#pragma lifecycle(startup)
let text = null;
async function goTo(name) {
const entry = Scenes.list().find((s) => s.name === name);
if (!entry) {
log('No scene named', name);
return;
}
text.setProps({ text: 'Loading ' + name + '… 0%' });
await Scenes.load(entry.id, {
onProgress: (loaded, total) => {
const percent = total > 0 ? Math.round((loaded / total) * 100) : 100;
text.setProps({ text: 'Loading ' + name + '… ' + percent + '%' });
},
});
text.setProps({ text: '' });
log('Now in', scene.name);
}
function startup() {
text = findEntity('Loading Text').getComponent(UILabelComponent);
text.setProps({ text: '' });
on('level/goto', (data) => goTo(data.name));
}

How it works:

  • #pragma dont_unload() carries this script’s entity, and everything under it, into the new scene, so the code after await Scenes.load runs.
  • onProgress(loaded, total) is called as the new scene’s assets load. The guard on total avoids dividing by zero for a scene with nothing to load.
  • After the load, scene is the new scene, so scene.name names it.
  • Another script starts a switch with emit('level/goto', { name: 'level-2' }).

4. A game manager that lives across levels

Section titled “4. A game manager that lives across levels”

A single manager keeps the score and the level number, and moves on to the next level when one is complete.

GameManager.jx
#pragma dont_unload()
#pragma lifecycle(startup)
const game = Singleton.get('game', () => ({ level: 1, coins: 0 }));
function idOf(name) {
const entry = Scenes.list().find((s) => s.name === name);
return entry ? entry.id : undefined;
}
function startup() {
on('coin/collected', () => {
game.coins += 1;
});
on('level/complete', () => {
const nextId = idOf('level-' + (game.level + 1));
if (!nextId) {
emit('game/finished', { coins: game.coins });
return;
}
game.level += 1;
Scenes.load(nextId);
});
}

How it works:

  • The entity is marked Don’t Unload, so the script and its listeners keep running in every level.
  • Singleton.get('game', factory) creates the game state once. Any script in any level reads the same object, for example Singleton.game.coins.
  • The next level’s name is built from the level number; when there is none, the script announces the end of the game instead.

The first level spawns the player from a template; later visits to the level find the existing one.

PlayerSpawner.jx
#pragma lifecycle(startup)
function startup() {
if (findEntity('Player')) {
log('Player already here');
return;
}
const player = spawn('Player Template', { position: { x: 0, y: 0, z: 0 }, enabled: true });
player.name = 'Player';
player.addComponent(new DontUnloadComponent());
log('Player spawned');
}

How it works:

  • findEntity('Player') finds a player carried in from an earlier level, so a second one is never made.
  • spawn copies the disabled Player Template entity of the scene; enabled: true switches the copy on.
  • Adding a DontUnloadComponent marks the new player, so it follows the visitor from level to level.

load and unload take an id, and throw for anything that is not in Scenes.list().

Wrong
Scenes.load('Level Two'); // throws: a name, not an id
Right
const entry = Scenes.list().find((s) => s.name === 'Level Two');
if (entry) Scenes.load(entry.id);

A script in the scene being replaced stops with it, and its await never resumes.

Wrong
async function next() {
await Scenes.load(nextId);
emit('level/started'); // never runs: this script left with its scene
}
Right
#pragma dont_unload()
// …the same function now runs to the end, because this entity is carried along

Or emit the signal from a script in the new scene’s startup.

Wrong
function startup() {
await Scenes.load(hudId, { additive: true });
}
Right
async function startup() {
await Scenes.load(hudId, { additive: true });
}

Scenes.load and Scenes.unload throw in editor code, because they would change the scene being edited. Use them in play hooks and listeners only. list, active and find are fine in both.

A Don’t Unload entity that is saved in a level which loads more than once, or spawned on every visit, piles up copies. Keep it in a scene that loads once, or check with findEntity before spawning, as example 5 does.