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.
Before you start
Section titled “Before you start”This page assumes you know what an entity and a component are. If not, read these first:
- Key concepts in Getting started: worlds, scenes, entities, components and Behaviors.
- Write your first script: a step-by-step tutorial that spins an object and reacts to a click.
- Working with entities and Components: the objects a script works on.
Behaviors and Behavior entities
Section titled “Behaviors and Behavior entities”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. |
execution |
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:
#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.
A first look
Section titled “A first look”This script spins its parent, and makes it hop each time the player presses Space:
#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 slotlines declarespeedandhopHeight: fields the editor shows, and variables the script reads. #pragma lifecyclenames the hooks the engine calls:startuponce,updateevery frame,disposeat the end.logwrites to the script log.Input.keyboardandKeyare covered in Input;Tweenin Time and tweens.
The same idea, live: a box that spins and changes colour when clicked.
A box that spins every frame and takes a new colour when you click it: a Behavior script, a Selectable and a Signal Emitter.
Click the box. Drag to orbit the camera, scroll to zoom.
How a script runs
Section titled “How a script runs”- Preprocess. The directives, the lines that start with
#, are applied: macros expand,#ifblocks are kept or dropped, slots and hooks are declared, and modules from URLs load. - Check. The result is checked against the language rules. A failure stops the script with a message naming the line.
- 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,
selfandscenealready hold their values here. - Start. On the next frame,
startupruns. - Tick. From the frame after,
updateruns every frame, and the script’sonandoncelisteners hear the signals they listen to. All scripts share one loop: they run, and hear signals, in theirexecutionIndexorder, lowest first. - Stop. When the Behavior is removed, its entity is destroyed or its scene unloads,
disposeruns and everything the script took is released: listeners, timers, tweens and requests.
Lifecycle hooks covers every hook, their order, pausing and async hooks.
Play code and editor code
Section titled “Play code and editor code”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.
The sandbox
Section titled “The sandbox”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., 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.
Language rules
Section titled “Language rules”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. 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.
Logs and errors
Section titled “Logs and errors”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.
Examples
Section titled “Examples”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.
1. A collectible coin
Section titled “1. A collectible coin”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.
#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');}A coin that spins until it is clicked, then announces score/add, shrinks with an awaited Tween and destroys itself.
Click the coin to collect it. Drag to orbit the camera, scroll to zoom.
How it works:
collectis declared abovestartup, 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;awaitis allowed becausecollectisasync.destroy(coin)removes the coin with everything under it, this Behavior entity included, sodisposeruns and the script’s listeners are released.
Common mistakes
Section titled “Common mistakes”Using this instead of self
Section titled “Using this instead of self”function startup() { this.parent.rotation.y = 1; // `this` is not the entity}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.
function update(dt) { self.rotation.y += dt; // turns the invisible Behavior entity}function update(dt) { self.parent.rotation.y += dt; // turns the object the script sits under}Expecting scripts to run in the editor
Section titled “Expecting scripts to run in the editor”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.
Calling a function declared further down
Section titled “Calling a function declared further down”The checker requires every name, functions included, to be declared above the code that uses it.
#pragma lifecycle(startup)function startup() { greet();}function greet() { log('hello');}#pragma lifecycle(startup)function greet() { log('hello');}function startup() { greet();}Using await at the top level
Section titled “Using await at the top level”const data = await HttpRequest.get('https://api.example.com/level.json').json();#pragma lifecycle(startup)let data = null;async function startup() { data = await HttpRequest.get('https://api.example.com/level.json').json();}Using browser timers
Section titled “Using browser timers”setTimeout and setInterval are undefined in a script.
setTimeout(() => log('later'), 1000);delay(() => log('later'), 1000);Newer syntax and var
Section titled “Newer syntax and var”var count = 0;count ??= 1;let count = 0;if (count == null) count = 1;