Skip to content

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.

A script names its hooks in one #pragma lifecycle(...) line. The engine calls only the hooks it names:

AllHooks.jx
#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:

Renamed.jx
#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 lifecycle only runs its top-level code, once, when it loads.
  • #pragma lifecycle is not allowed in an #editor_only script.
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 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.

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.

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:

  1. A script that has not started runs startup, and nothing else this frame.
  2. 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.

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: no update.
  • 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(...).

Switching
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, with startup, the first time it is enabled.
  • on and once listeners, delay timers and tweens keep running while the script is paused. Stop them in disable if they should not.
  • dispose does not run on disable. It runs only when the script stops for good.

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. update starts on the frame after startup begins, even while startup is still awaiting. Guard update with a flag.
  • A rejected promise is reported like a thrown error: the script stops, its dispose runs, and the error goes to the script log.
  • When the script stops, its pending delay timers are cancelled and its HttpRequest calls are aborted. An await Scenes.load(...) of a scene that unloads this script never resumes. See Scene switching.
  • await is only allowed inside an async function, never at the top level.

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:

SafeLoad.jx
#pragma lifecycle(startup)
async function startup() {
try {
await Scenes.load('hud', { additive: true });
} catch (error) {
log('no HUD:', error.message);
}
}

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.

Pendulum.jx
#pragma lifecycle(startup, update)
const SWING = DEG_TO_RAD(30); // largest angle
const PERIOD = 2; // seconds for a full swing
let arm = null;
function startup() {
arm = self.parent;
}
function update(delta, time) {
arm.rotation.z = Math.sin((time / PERIOD) * M_TAU) * SWING;
}

How it works:

  • startup keeps the parent in arm once.
  • update computes the angle from time alone, so it never drifts.
  • DEG_TO_RAD and M_TAU are predefined by the preprocessor. See Directives.

on listeners keep running while a script is disabled. This script stops listening in disable and starts again in enable.

DoorListener.jx
#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:

  • on returns a function that stops the listener; the script keeps it in stopListening.
  • disable calls it, so nothing reacts while the script is off.
  • enable listens again. listen is declared first because the hooks use it.

An async startup downloads a level description, and update waits for it.

LevelSpinner.jx
#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: update runs from the next frame, so it returns early until ready is true.
  • try … catch keeps a failed request from stopping the script.
  • If the script stops while the request is in flight, the request is aborted for you.

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.

Shield.jx
// 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;
});
}
Health.jx
// 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 damage to 0 and the health script sees that.
  • Another script raises the hit with emit('player/hit', { damage: 10 }).

A function named update is only called when #pragma lifecycle names it.

Wrong
function update(dt) {
self.parent.rotation.y += dt; // never called
}
Right
#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”
Wrong
#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
}
Right
#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;
}
Wrong
function update() {
self.parent.position.x += 0.05; // faster on faster devices
}
Right
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.

A second #pragma lifecycle is an error. List every hook in one line: #pragma lifecycle(startup, update, dispose).