Lifecycle hooks
Updated
A Behavior’s hooks are the functions the engine calls at fixed moments of the script’s life: when it starts, every frame while it runs, when it pauses and resumes, and when it stops for good. You never call a hook yourself; you declare which ones the script has, and the engine calls them at the right time. This page lists every hook and its signature, how to declare them with #pragma lifecycle, the order scripts run in, what enabling and disabling do, and how async hooks behave.
Before you start
Section titled “Before you start”- Behavior scripts: what a Behavior is, and
self. - Directives:
#pragma lifecycleis one of the script’s directives. - Events and signals:
onandonce, which scripts usually call instartup.
Declaring hooks
Section titled “Declaring hooks”A script names its hooks in one #pragma lifecycle(...) line. The engine calls only the hooks it names:
#pragma lifecycle(startup, update, enable, disable, dispose)
async function startup() { log('started'); }function update(dt, time) { self.parent.rotation.y += dt; }function disable(source) { log('paused by', source.name); }function enable(source) { log('resumed by', source.name); }function dispose() { log('gone'); }To use other function names, write hook=function:
#pragma lifecycle(startup=init, update=tick)
function init() { log('ready'); }function tick(dt) { self.parent.position.x += dt; }- Declare any subset of the five hooks, in any order.
- A script has at most one
#pragma lifecycle. A second one is an error: declare every hook in the first. - The names must be valid JavaScript names, and the functions must exist in the script.
- A script without
#pragma lifecycleonly runs its top-level code, once, when it loads. #pragma lifecycleis not allowed in an#editor_onlyscript.
The hooks
Section titled “The hooks”| Hook | Signature | When it runs |
|---|---|---|
startup |
startup() |
Once, on the first frame after the script loads. May be async. |
update |
update(delta, time) |
Every frame from the frame after startup. delta is the seconds since the last frame, at most 1/12 s. time is the seconds the application has been playing. |
disable |
disable(source) |
When the script is switched off. source is what was switched off. |
enable |
enable(source) |
When the script is switched back on. source is what was switched on. |
dispose |
dispose() |
Once, when the script stops for good: its Behavior is removed, its entity destroyed, its scene unloaded, or its code changed. |
Top-level code
Section titled “Top-level code”Top-level code is not a hook, but it runs first: once, when the script loads, a frame before startup. Slot variables, self and scene are ready there, so it is a good place for constants and for lookups that do not depend on other scripts.
Moving by delta
Section titled “Moving by delta”update runs once per frame, and frames do not all last the same time: a fast device draws more of them each second than a slow one. Multiply every change by delta so it is expressed per second, and the world moves at the same speed everywhere. Because delta is capped at 1/12 s, a long stall (a tab in the background, a slow load) never makes an object jump far.
Order within a frame
Section titled “Order within a frame”When a scene starts, it can be drawn while its enabled Behaviors load. Their startup hooks run together, once they have all loaded; a script that imports a slow URL module delays the group.
Each frame, the engine walks the running scripts by their Behavior’s executionIndex, lowest first. Scripts with the same index run in the order they loaded. For each script:
- A script that has not started runs
startup, and nothing else this frame. - Otherwise it runs
update(delta, time).
So when script A’s index is lower than script B’s, A’s update runs before B’s. Change executionIndex on the Behavior to change the order; the engine re-sorts on its own.
Signals follow the same order. When a signal is emitted, the scripts listening to it with on or once hear it lowest executionIndex first, right away, inside emit.
Behaviors run after the components’ own per-frame work, and before the components’ late updates. When a scene unloads, its scripts’ dispose hooks also run in execution order.
Enable and disable
Section titled “Enable and disable”A script runs while its Behavior, its entity and every ancestor entity are enabled. When one of them is switched off:
disable(source)runs, and the script pauses: noupdate.- Its variables keep their values.
When everything above it is on again, enable(source) runs and the script carries on where it was.
source is what was switched: the entity (self or an ancestor) for entity.setEnabled(...), or the Behavior component (self.getComponent(BehaviorComponent)) for behavior.setEnabled(...).
const car = findEntity('Car');car.setEnabled(false); // Wheel script: disable(car) Bolt script: disable(car)car.setEnabled(true); // Wheel script: enable(car) Bolt script, itself disabled: nothing- A child that is itself disabled stays silent when its parent comes back. It resumes only when everything above it is on.
- Neither hook runs before
startup. A script that starts disabled just starts, withstartup, the first time it is enabled. onandoncelisteners,delaytimers and tweens keep running while the script is paused. Stop them indisableif they should not.disposedoes not run on disable. It runs only when the script stops for good.
Async hooks
Section titled “Async hooks”Any hook may be async, and await is allowed inside it. Use this to wait for a download, a scene load or a tween before carrying on.
- The engine does not wait for an async hook.
updatestarts on the frame afterstartupbegins, even whilestartupis still awaiting. Guardupdatewith a flag. - A rejected promise is reported like a thrown error: the script stops, its
disposeruns, and the error goes to the script log. - When the script stops, its pending
delaytimers are cancelled and itsHttpRequestcalls are aborted. Anawait Scenes.load(...)of a scene that unloads this script never resumes. See Scene switching. awaitis only allowed inside anasyncfunction, never at the top level.
Errors
Section titled “Errors”An error thrown by any hook stops the script. Its dispose runs, what it holds is released, and the error goes to the script log with the hook’s name. Catch the errors you expect:
#pragma lifecycle(startup)
async function startup() { try { await Scenes.load('hud', { additive: true }); } catch (error) { log('no HUD:', error.message); }}Examples
Section titled “Examples”1. A pendulum driven by time
Section titled “1. A pendulum driven by time”update receives both the frame’s delta and the total playing time. A swing that depends only on time stays in step however irregular the frames are.
#pragma lifecycle(startup, update)
const SWING = DEG_TO_RAD(30); // largest angleconst PERIOD = 2; // seconds for a full swinglet arm = null;
function startup() { arm = self.parent;}
function update(delta, time) { arm.rotation.z = Math.sin((time / PERIOD) * M_TAU) * SWING;}An arm that swings from the total playing time passed to update, so it never drifts however irregular the frames are.
Watch the pendulum swing. Drag to orbit the camera, scroll to zoom.
How it works:
startupkeeps the parent inarmonce.updatecomputes the angle fromtimealone, so it never drifts.DEG_TO_RADandM_TAUare predefined by the preprocessor. See Directives.
2. Pause listeners with the script
Section titled “2. Pause listeners with the script”on listeners keep running while a script is disabled. This script stops listening in disable and starts again in enable.
#pragma lifecycle(startup, enable, disable)
let stopListening = null;
function listen() { stopListening = on('door/open', (data) => log('door opened', data));}
function startup() { listen(); }function disable() { stopListening(); }function enable() { listen(); }How it works:
onreturns a function that stops the listener; the script keeps it instopListening.disablecalls it, so nothing reacts while the script is off.enablelistens again.listenis declared first because the hooks use it.
3. Load data before animating
Section titled “3. Load data before animating”An async startup downloads a level description, and update waits for it.
#pragma lifecycle(startup, update)
let ready = false;let data = null;
async function startup() { try { data = await HttpRequest.get('https://api.example.com/level.json').json(); ready = true; } catch (error) { log('could not load the level:', error.message); }}
function update(dt) { if (!ready) return; self.parent.rotation.y += data.spin * dt;}How it works:
- The engine does not wait for
startup:updateruns from the next frame, so it returns early untilreadyistrue. try…catchkeeps a failed request from stopping the script.- If the script stops while the request is in flight, the request is aborted for you.
4. Ordered reactions to one signal
Section titled “4. Ordered reactions to one signal”Two scripts listen to the same signal. The one with the lower executionIndex hears it first and can absorb the hit before the other one sees it.
// executionIndex: -1, so it hears the hit before the health script#pragma lifecycle(startup)
let charges = 2;
function startup() { on('player/hit', (hit) => { if (charges === 0) return; charges -= 1; log('Shield absorbed', hit.damage, '- charges left:', charges); hit.damage = 0; });}// executionIndex: 0#pragma lifecycle(startup)
let health = 100;
function startup() { on('player/hit', (hit) => { if (hit.damage === 0) return; health -= hit.damage; log('Health', health); });}How it works:
- Both scripts listen in
startup. When the hit is emitted, they hear it in execution order: the shield first. - Both callbacks receive the same data object, so the shield sets
damageto0and the health script sees that. - Another script raises the hit with
emit('player/hit', { damage: 10 }).
Common mistakes
Section titled “Common mistakes”Forgetting to declare a hook
Section titled “Forgetting to declare a hook”A function named update is only called when #pragma lifecycle names it.
function update(dt) { self.parent.rotation.y += dt; // never called}#pragma lifecycle(update)function update(dt) { self.parent.rotation.y += dt;}Assuming update waits for an async startup
Section titled “Assuming update waits for an async startup”#pragma lifecycle(startup, update)let config = null;async function startup() { config = await HttpRequest.get('https://api.example.com/config.json').json();}function update(dt) { self.parent.rotation.y += config.speed * dt; // config is still null on the first frames}#pragma lifecycle(startup, update)let config = null;async function startup() { config = await HttpRequest.get('https://api.example.com/config.json').json();}function update(dt) { if (!config) return; self.parent.rotation.y += config.speed * dt;}Moving by a fixed step per frame
Section titled “Moving by a fixed step per frame”function update() { self.parent.position.x += 0.05; // faster on faster devices}function update(dt) { self.parent.position.x += 3 * dt; // 3 metres a second everywhere}Expecting disable to stop timers and listeners
Section titled “Expecting disable to stop timers and listeners”on listeners, delay timers and tweens keep running while the script is paused. Stop them in disable, as in example 2, or check a flag in the callback.
Two #pragma lifecycle lines
Section titled “Two #pragma lifecycle lines”A second #pragma lifecycle is an error. List every hook in one line: #pragma lifecycle(startup, update, dispose).