Skip to content

Behavior scripts

Updated

A Behavior is a JavaScript script attached to an entity. It is how you give a world its logic: a door that opens when a button is pressed, a coin that spins and disappears when collected, a score that counts up, a level that loads the next one. This page explains where Behaviors live, how a script runs from the moment its scene starts until it stops, the sandbox it runs in, and the language rules every script is checked against before it runs.

This page assumes you know what an entity and a component are. If not, read these first:

A script is held by a Behavior component (BehaviorComponent, type comp-behavior). The component is data only: it stores the script’s source, its run order and the values of its editor fields. The scripting runtime reads it and runs the code.

Prop Type Default Description
code string '' The script source. Changing it restarts the script.
executionIndex integer 0 The run order against the other Behaviors, lowest first. Negative values are allowed. See Lifecycle hooks.
slotValues object {} The values of the script’s slots (editor fields), saved by the editor.
slotProps object {} Slot settings, such as a label or a maximum, that editor code changed.

In the editor you add a script as a Behavior entity (ent-behavior); the steps in XR Creator are in Add a behavior. It has a transform, so you can place it and parent it like any other entity. A new one starts with this code:

New Behavior
#pragma lifecycle(startup,update,dispose)
function startup() {
}
function update(delta,time) {
}
function dispose() {
}

self connects a script to the world: it is the entity the Behavior is on, the Behavior entity itself. The script’s own Behavior component is self.getComponent(BehaviorComponent).

To drive another object, put the Behavior entity under it in the hierarchy and use self.parent, or find the object by name with findEntity('Door'). An entity holds one Behavior; use several Behavior entities for several scripts.

This script spins its parent, and makes it hop each time the player presses Space:

SpinAndHop.jx
#pragma slot(ref=speed, type=Slider, min=0, max=10, step=0.1, default=2, group="Motion")
#pragma slot(ref=hopHeight, type=Number, min=0, max=5, default=1, group="Motion")
#pragma lifecycle(startup, update, dispose)
let target = null;
function startup() {
target = self.parent;
log('Spinning', target.name, 'at', speed, 'rad/s');
}
function update(dt) {
target.rotation.y += speed * dt;
if (Input.keyboard.isKeyReleased(Key.Space)) {
Tween.to(target.position, { y: target.position.y + hopHeight }, { duration: 0.25, repeat: 1, yoyo: true });
}
}
function dispose() {
log('Stopped');
}
  • The two #pragma slot lines declare speed and hopHeight: fields the editor shows, and variables the script reads.
  • #pragma lifecycle names the hooks the engine calls: startup once, update every frame, dispose at the end.
  • log writes to the script log. Input.keyboard and Key are covered in Input; Tween in Time and tweens.

The same idea, live: a box that spins and changes colour when clicked.

  1. Preprocess. The directives, the lines that start with #, are applied: macros expand, #if blocks are kept or dropped, slots and hooks are declared, and modules from URLs load.
  2. Check. The result is checked against the language rules. A failure stops the script with a message naming the line.
  3. Load. The script becomes an ordinary JavaScript function, which the browser’s own engine runs at full speed, with no interpreter in between; identical scripts share one compiled copy. Its top-level code runs once. Slot variables, self and scene already hold their values here.
  4. Start. On the next frame, startup runs.
  5. Tick. From the frame after, update runs every frame, and the script’s on and once listeners hear the signals they listen to. All scripts share one loop: they run, and hear signals, in their executionIndex order, lowest first.
  6. Stop. When the Behavior is removed, its entity is destroyed or its scene unloads, dispose runs and everything the script took is released: listeners, timers, tweens and requests.

Lifecycle hooks covers every hook, their order, pausing and async hooks.

Behavior scripts run in play only; the editor and play modes are compared in Editor and play.

A script can still carry editor code: functions that run when someone presses one of its buttons or edits one of its fields in the editor. That code lives between #editor_begin and #editor_end, or fills a whole #editor_only script, and it is absent from the player. See Editor scripts.

Play code Editor code
Runs Through the lifecycle hooks When a slot sends an event, or needs validating
Every global Yes Yes
slot(ref), a live handle to a slot No Yes
Editor: selection and viewport camera Throws Yes
Scenes.load, Scenes.unload Yes Throws

Editor and play explains the two modes for the whole runtime.

A script sees only what the runtime gives it: its globals, THREE (raw three.js code: meshes, materials, vectors and math), and the standard JavaScript library (Math, JSON, Intl, Date, Map, Set, Promise, typed arrays, TextEncoder, structuredClone, URLSearchParams, AbortController and the like).

Every other name of the web page is undefined inside a script: window, document, globalThis, fetch, XMLHttpRequest, WebSocket, localStorage, setTimeout, setInterval, requestAnimationFrame and eval. Use the runtime’s own tools instead:

Instead of Use
setTimeout, setInterval delay, debounce, throttle, or the update hook. See Time and tweens.
fetch HttpRequest. See Data and utilities.
window.location, window.open WebBrowser. See Device and haptics.
Global variables shared between scripts #pragma export or Singleton. See Modules.

The script body runs in strict mode: assigning a name that was never declared throws a ReferenceError. Every injected name is a constant: scene = null throws, and let scene or const camera does not compile.

Resources a script starts (listeners, timers, tweens, requests) belong to it. When the script stops, the runtime releases them for you.

Every script is checked before it runs. A script that breaks a rule does not start, and the script log says which line is wrong.

Rule Fails Fix
Declare with let or const var count = 0; let count = 0;
Declare before use, functions included function update() { step(); } above function step() {} Put step above update.
Only known names fooo(); Fix the name, or declare it.
JavaScript up to ES2020 a ??= 1;, 1_000, class A { x = 1; } if (a == null) a = 1;, 1000, assign fields in the constructor.
No await outside an async function await Scenes.load('hud'); at the top level Put it in async function startup().
No new for side effects alone new Foo(); const foo = new Foo();

Optional chaining (a?.b), nullish coalescing (a ?? b), async and await inside functions, classes with methods, destructuring and template literals all work.

log(...values) writes a line to the script log, where you also find every error. console.log, console.info, console.warn and console.error write there too, at a level.

An error thrown by a hook, an on callback or a timer stops the script: its dispose runs and the error goes to the script log, with the hook’s name. A preprocessing or checking error stops the script before it starts. Catch the errors you expect with try … catch.

The first scripts, a spinner and a click handler, are built step by step in Write your first script, and a script with editor fields in the Scripting walkthrough.

A realistic script: the coin spins, and when clicked it announces itself, shrinks and removes itself from the scene. The coin carries a Selectable and a Signal Emitter whose signal matches the clickSignal slot.

Coin.jx
#pragma slot(ref=clickSignal, type=String, default="coin/clicked", tooltip="The signal of the coin's Signal Emitter")
#pragma slot(ref=value, type=Integer, min=1, max=100, default=1)
#pragma slot(ref=spin, type=Slider, min=0, max=10, default=3)
#pragma lifecycle(startup, update, dispose)
let coin = null;
let collected = false;
async function collect() {
collected = true;
emit('score/add', { points: value });
await Tween.to(coin.scale, { x: 0, y: 0, z: 0 }, { duration: 0.3, ease: Ease.InBack });
destroy(coin);
}
function startup() {
coin = self.parent;
on(clickSignal, (event) => {
if (collected || event.eventType !== EventType.Selectable.Select) return;
findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again
collect();
});
}
function update(dt) {
if (!collected) coin.rotation.y += spin * dt;
}
function dispose() {
log('Coin removed');
}

How it works:

  • collect is declared above startup, because a function must be declared before the code that uses it.
  • emit('score/add', …) raises a signal any other script can listen to, such as a score keeper.
  • await Tween.to(...) waits for the shrink to finish; await is allowed because collect is async.
  • destroy(coin) removes the coin with everything under it, this Behavior entity included, so dispose runs and the script’s listeners are released.
Wrong
function startup() {
this.parent.rotation.y = 1; // `this` is not the entity
}
Right
function startup() {
self.parent.rotation.y = 1;
}

Moving the Behavior entity instead of the object

Section titled “Moving the Behavior entity instead of the object”

self is the Behavior entity, which draws nothing. Rotating it turns only what is under it. To drive the object the script belongs to, place the Behavior entity under that object and use its parent.

Wrong
function update(dt) {
self.rotation.y += dt; // turns the invisible Behavior entity
}
Right
function update(dt) {
self.parent.rotation.y += dt; // turns the object the script sits under
}

Scripts run in play only. In the editor the scene stays still, so a spinner does not spin and startup does not run until you press Play. For tools that help you author, use Editor scripts.

The checker requires every name, functions included, to be declared above the code that uses it.

Wrong
#pragma lifecycle(startup)
function startup() {
greet();
}
function greet() {
log('hello');
}
Right
#pragma lifecycle(startup)
function greet() {
log('hello');
}
function startup() {
greet();
}
Wrong
const data = await HttpRequest.get('https://api.example.com/level.json').json();
Right
#pragma lifecycle(startup)
let data = null;
async function startup() {
data = await HttpRequest.get('https://api.example.com/level.json').json();
}

setTimeout and setInterval are undefined in a script.

Wrong
setTimeout(() => log('later'), 1000);
Right
delay(() => log('later'), 1000);
Wrong
var count = 0;
count ??= 1;
Right
let count = 0;
if (count == null) count = 1;