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.
Before you start
Section titled “Before you start”- Scenes explains base, additive and ruling scenes, and why a scene starts as saved each time it loads.
Scenes.loadreturns a promise. To wait for it, the calling function must beasync; see Lifecycle hooks.
The Scenes global
Section titled “The Scenes global”await Scenes.load('level-2'); // replace the active scenesawait Scenes.load('hud', { additive: true }); // add on topawait Scenes.unload('hud'); // take it away and free itScenes.list(); // [{ id, name }] of every sceneScenes.active(); // ids of the active scenes, base firstScenes.find('hud'); // a loaded scene, by name or idThe 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(name |
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.
loadandunloadthrow for an id that is not inlist(). Use the idslist()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,
loadandunloadthrow, because they would change the scene being edited.list,activeandfindwork everywhere.
Leaving your own scene
Section titled “Leaving your own scene”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
disposehook then runs as usual, and its listeners, timers and tweens are released. - The promise it awaits never settles, so nothing after the
awaitruns against a scene that is gone. - Loading that scene again starts its scripts afresh, from
startup.
#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.
Keeping an entity: Don’t Unload
Section titled “Keeping an entity: Don’t Unload”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, classDontUnloadComponent). 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.
startupdoes not run again anddisposedoes not run. Its ownawait Scenes.load(…)resolves. scenethen refers to the new scene, andfindEntity,spawnanddestroywork 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.
What survives a switch
Section titled “What survives a switch”| 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 |
Examples
Section titled “Examples”1. A portal to the next level
Section titled “1. A portal to the next level”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.
#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);}A two-scene project: clicking the portal looks up the scene named level-2 with Scenes.list() and loads it with Scenes.load.
Click the ring to travel to level 2. Drag to orbit the camera, scroll to zoom.
How it works:
- The
targetslot lets each portal in the editor point to a different scene, by name. startupturns the name into an id once, withScenes.list(), and stops early when the scene does not exist.- The
leavingflag 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
awaitthe load.
2. Show and hide a HUD
Section titled “2. Show and hide a HUD”Pressing H adds a HUD scene on top of the level, and pressing it again takes it away.
#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: truekeeps 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.unloadfrees the HUD; showing it again builds it fresh.- The
busyflag ignores key presses while a load or unload is in progress, andtry/catchreports a failure instead of stopping the script.
3. A loading bar
Section titled “3. A loading bar”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.
#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 afterawait Scenes.loadruns.onProgress(loaded, total)is called as the new scene’s assets load. The guard ontotalavoids dividing by zero for a scene with nothing to load.- After the load,
sceneis the new scene, soscene.namenames 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.
#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 exampleSingleton.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.
5. Spawn the player only once
Section titled “5. Spawn the player only once”The first level spawns the player from a template; later visits to the level find the existing one.
#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.spawncopies the disabledPlayer Templateentity of the scene;enabled: trueswitches the copy on.- Adding a
DontUnloadComponentmarks the new player, so it follows the visitor from level to level.
Common mistakes
Section titled “Common mistakes”Passing a scene name to load
Section titled “Passing a scene name to load”load and unload take an id, and throw for anything that is not in Scenes.list().
Scenes.load('Level Two'); // throws: a name, not an idconst entry = Scenes.list().find((s) => s.name === 'Level Two');if (entry) Scenes.load(entry.id);Expecting code after the switch to run
Section titled “Expecting code after the switch to run”A script in the scene being replaced stops with it, and its await never resumes.
async function next() { await Scenes.load(nextId); emit('level/started'); // never runs: this script left with its scene}#pragma dont_unload()// …the same function now runs to the end, because this entity is carried alongOr emit the signal from a script in the new scene’s startup.
Using await outside an async function
Section titled “Using await outside an async function”function startup() { await Scenes.load(hudId, { additive: true });}async function startup() { await Scenes.load(hudId, { additive: true });}Switching scenes from editor code
Section titled “Switching scenes from editor code”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.
Duplicating a Don’t Unload entity
Section titled “Duplicating a Don’t Unload entity”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.