Skip to content

Globals

Updated

A global is a name the runtime gives every Behavior script before it runs: self, scene, findEntity, Tween, Input, THREE and many more. You use a global like a variable you declared yourself, but you never declare it, import it or create it. This page lists every global by what it is for, explains the rules that apply to all of them, and points to the page that teaches each group in depth.

  • A Behavior script is JavaScript attached to an entity. Read Behavior scripts if you have not written one yet.
  • Hooks such as startup and update are declared with #pragma lifecycle(...). See Lifecycle hooks.
  • The complete, generated list of globals with their full descriptions is in the Globals reference.

Globals are constants. The runtime injects each one as a constant. You can read it and call its methods, but you cannot assign to it (scene = null throws) or redeclare it (let scene does not compile).

The browser is hidden. A script runs in a sandbox. Page objects such as window, document, globalThis, fetch, localStorage, setTimeout, setInterval, requestAnimationFrame and eval are undefined inside a script. The runtime gives you a replacement for each job:

Instead of Use Page
setTimeout, setInterval delay, debounce, throttle, or the update hook Time and tweens
fetch, XMLHttpRequest HttpRequest Data and utilities
window.location, window.open WebBrowser Input and interaction
Global variables shared between scripts #pragma export / #pragma import, or Singleton Modules

Strict mode. The script body runs in strict mode: assigning a name that was never declared throws a ReferenceError.

Resources follow the script. Most globals that start something (listeners, timers, tweens, HTTP requests, devices, streams, textures) tie it to the script. When the script stops, because its entity is destroyed, its scene unloads or its code changes, the runtime stops and frees everything the script started. You rarely need to clean up by hand.

These globals reach the script’s own entity, the scene it is in, and the other entities of that scene. Scene and entities covers them in depth.

GlobalWhat it is
selfThe entity the Behavior is on: self.position, self.getComponent(...). Its own Behavior is self.getComponent(BehaviorComponent).
sceneThe current scene fragment; live, so it always reflects the loaded scene. To delete an entity use scene.destroy(entity): it stops its scripts and frees its memory. scene.remove(entity) (and scene.clear()) stop the scripts but keep the memory, for an entity you will add back later.
findEntityFind an entity in the current scene by id, a map read fine every frame, or else by name among its entities.
findObjectFind any object in the current scene by name, a bone or a mesh inside a model too. Walks the scene: look up once and keep it.
spawnCopy an entity already in the scene (by name, or the entity itself) and add the copy with options.
destroySame as scene.destroy: remove an entity (or id) and its subtree, disposing them and stopping their scripts.
isEntityWhether an object is an Entity, and so has components.
cameraThe camera the player sees through
audioListenerShared listener attached to the active camera; live, undefined until rendering starts.
CameraDirectorCut between cameras by name or id: switchTo(name), switchToMain(); current and main are the camera entities.
EnvironmentProject variables, read only: Environment.get(name, fallback) returns the loaded value or fallback when absent or still an unresolved reference.

Two more globals in this family have pages of their own: Scenes loads, unloads and lists scenes (Scene switching), and Editor reaches the editor’s selection and viewport camera from editor code only (Editor scripts).

GlobalWhat it is
ScenesSwitch scenes: await Scenes.load(id), load(id, { additive: true }), unload(id), list(), active().
EditorEditor tools only (#editor_only, #editor_begin): selection(), select(entities), camera. Throws in play.

Signals are named messages that scripts and components send to each other. See Events and signals.

GlobalWhat it is
emitRaise a signal, with optional data, for every script and the app.
onCall callback(data) right away each time signal is emitted; returns a function that stops it. Released with the script.
onceCall callback(data) the next time signal is emitted, then stop; returns a function that stops it sooner. Released with the script.
offStop every listener this script added with on or once for signal; other scripts keep theirs.
EventTypeEvery event type a script can hear, by who sends it: compare them rather than typing the strings.

These globals schedule code and animate values. See Time and tweens.

GlobalWhat it is
TimeMeasure with Time.now(), Time.since(start); game time: Time.scale, pause(), resume(), isPaused().
TweenAnimate any object's numbers: Tween.to(mesh.position, { x: 5 }, { duration: 1 }), from, value, stop; awaitable.
EaseThe easings, for { ease: Ease.OutCubic }: Linear, and In, Out and InOut of each curve (Quad, Cubic, Quart, Sine, Expo, Back, Elastic, Bounce). In starts slow, Out ends slow, InOut does both; Back overshoots a little, Elastic springs, Bounce bounces. Any function of progress 0..1 works as well.
Global What it does
delay(fn, ms, ...args) Runs fn(...args) once, ms milliseconds of game time from now. Returns a function that cancels it.
debounce(fn, ms) Returns a version of fn that runs once, ms after the last of a burst of calls.
throttle(fn, ms) Returns a version of fn that runs at most once every ms.

Keyboard, mouse, touch, XR controllers, sensors and facts about the device. These are covered in Input and interaction.

GlobalWhat it is
InputEvery input device: keyboard, mouse, touch, XR, accelerometer, gyroscope, microphone, device camera, location.
KeyDefines the values for standard keys
MouseButtonThe MouseButton enum provides constants representing the different mouse buttons.
DevicePlatform facts for scripts that adapt to the device they run on.
TorchThe phone's torch, by its back camera: await Torch.on(), off(), toggle(), isOn().
HapticsVibration on whatever the player has: XR controllers in an XR session, a gamepad's rumble when one is connected, the phone otherwise.
WebBrowserRead the browser location and open new tabs.

XRButton names the buttons of an XR controller (XRButton.Trigger, XRButton.Squeeze, XRButton.A…). See XR.

Rays and coordinate conversions, covered in Input and interaction.

GlobalWhat it is
GraphicsRaycasterA ray against what is drawn: meshes, lines, points and sprites, down to the triangle. A native THREE.Raycaster; see Raycaster for how to use it. Hidden objects and objects excluded by the current local view are never hit.
PhysicsRaycasterA ray against colliders, in the physics world: one query over a few simple shapes instead of every triangle, and exactly what the physics blocks. A native THREE.Raycaster too; see Raycaster for how to use it.
XRRaycasterA ray against the real world, asked of the device (a WebXR hit test): the floor, walls, tables and anything else it understands, in an immersive session. The device only casts from what it tracks, so the rays start there:
CoordinateSpaceConversions between the screen, the world, and an object's own space.

Shared rooms where entities replicate between visitors. See Multiplayer.

GlobalWhat it is
NetworkReplicate objects and traits: replicate(object, options), unreplicate, of, define(kind, build, setup), spawn(kind, data, options), subscribe(partition), unsubscribe(partition); connected, peerId, peers, peerCount, interestCenter.
NetworkTraitTypeEvery trait a Networkable can replicate: traits: [NetworkTraitType.Transform, NetworkTraitType.PointLight].
NetworkCommandEvery command the room server defines: Network.command(NetworkCommand.ReactionSend, { reaction: '👍' }).

Toasts and dialogs shown from a script. See Notifications.

GlobalWhat it is
NotificationServiceNotifications, passive or asking: show(type, data, { anchor | position, duration, signal }), the answer on signal; update(id, data, options), define(key, build), dismiss(type), has, isOpen.
NotificationTypeThe built-in notifications: Info, Success, Warning, Error, Compact.

HTTP, canvases, random numbers, pools, shared objects, streams, fonts, THREE and logging. See Data and utilities and Modules.

GlobalWhat it is
HttpRequestHTTP requests, cancelled when the script is released: get, post, …, request, and extend for a client with its own defaults.
SURLRoute a URL through the configured CORS proxy. Exposed to scripts as SURL.
CanvasCanvases for scripts that draw their own images: labels, minimaps, dynamic textures.
RandomThe shared generator scripts use as Random: every method, with examples, is on RandomGenerator. Frozen, so no script can change it for the others.
ObjectPoolReuses objects instead of creating and discarding them, for things that come and go often: bullets, particles, floating damage numbers.
SingletonNamed shared instances for this app: Singleton.get(key, factory), then Singleton.key.
StreamsLive streams by name, for Media Stream components: create(id, { video, audio }) then writeVideoFrame / writeAudioFrame, publish(id, Input.camera.stream()), ids(), has(id), on(id, live => …). Optional RTC: room.state, room.subscribe, room.connect/disconnect, and explicit await room.publish(source) / await room.unpublish(source) for mic, camera and screen.
FontsThe app's font families: await Fonts.register(family, url, { weight, label }) for this session, unregister, has(family), families.
THREERaw three.js in a Behavior: meshes, materials, vectors, colours and math.
logWrite values to the script log.
consoleThe app logger, with the usual console methods.
LoggerThe app logger: log, info, warn, error. Also reachable as console.

ShaderPreset lists and registers the shader presets a Shader Material can draw. See Graphics.

The preprocessor replaces these names in your source before the script runs. They cost nothing at run time. Directives explains how they work, along with device flags such as IS_MOBILE.

GlobalWhat it is
M_PIπ, half a turn in radians.
M_TAU2π, a full turn in radians.
M_HALF_PIπ/2, a quarter turn in radians.
EPSILONFloat tolerance for positions and angles (1e-6).
MAX_INTLargest safe integer (Number.MAX_SAFE_INTEGER).
MIN_INTSmallest safe integer (Number.MIN_SAFE_INTEGER).
SCRIPTING_RUNTIME_VERSIONVersion number of the scripting runtime.
DEG_TO_RADConvert degrees to radians.
RAD_TO_DEGConvert radians to degrees.
ASSERTThrow Assertion failed when the condition is false.

ASSERT(x) compares with == false: it throws for false, 0, '' and '0', but not for null or undefined. Write ASSERT(target != null) to test those.

Every concrete component class and every entity class is a global under its class name. You pass a component class to getComponent to reach a component, and you construct an entity class with new to build a new entity:

const light = self.parent.getComponent(PointLightComponent);
light.setProps({ intensity: 2 });
const lamp = new PointLightEntity();
scene.add(lamp);
Call What it returns
entity.getComponent(Class) The component of that class, or undefined. Also accepts the type string, such as 'comp-point-light'.
entity.getComponents(Class) Every component of that class, for types an entity can hold several of (colliders, Signal Emitters). A new array each call.
entity.getAllComponents() Every component on the entity, in the order added.

Four abstract base classes are globals too, so you can find a component whatever its concrete kind:

Base class Use
MaterialComponent getComponent(MaterialComponent) returns the entity’s material, whichever kind it is.
PhysicsColliderComponent getComponents(PhysicsColliderComponent) lists every collider shape.
ModelLoaderComponent getComponent(ModelLoaderComponent).props.src is the model’s source, whatever its format.
DynamicBoneComponent getComponents(DynamicBoneComponent) lists the velocity and spring bones.

Other abstract bases are not globals: use the concrete class instead, such as PerspectiveCameraComponent. Each component’s own props, methods and events are documented on its reference page, such as Point Light, and the model behind them in Components.

Scripts get the JavaScript built-ins that compute, and nothing that reaches the page: Object, Array, Function, Boolean, Number, BigInt, String, Symbol, Reflect, Math, JSON, Intl, Date, RegExp, isFinite, isNaN, parseFloat, parseInt, the URI encoders, URLSearchParams, atob, btoa, TextEncoder, TextDecoder, Map, Set, WeakMap, WeakSet, ArrayBuffer, DataView, every typed array, structuredClone, Promise, AbortController, Blob, FormData and the error classes.

Timers, queueMicrotask, WeakRef, FinalizationRegistry, SharedArrayBuffer and Atomics are left out. The language is ES2020: newer syntax such as ??= or numeric separators (1_000) does not compile.

A first look at the most common globals: the script’s own Behavior, its entity and its scene.

WhereAmI.jx
#pragma lifecycle(startup)
function startup() {
log('Behavior entity:', self.name);
log('Attached under:', self.parent.name);
log('Scene:', scene.name, 'with', scene.entities.size, 'entities');
log('Scripting runtime version', SCRIPTING_RUNTIME_VERSION);
}

How it works

  • self is the entity the script’s Behavior is on.
  • self.parent is the object the Behavior entity sits under: a common way to drive one object from a script.
  • scene.entities is a Map of every entity in the scene, by id.
  • log writes to the script log, and SCRIPTING_RUNTIME_VERSION is a constant the preprocessor fills in.

Turn the parent a quarter turn in degrees and tint its material, whatever kind of material it has.

QuarterTurn.jx
#pragma lifecycle(startup)
function startup() {
const target = self.parent;
target.setRotation(0, DEG_TO_RAD(90), 0);
const material = target.getComponent(MaterialComponent);
if (material) material.setProps({ color: '#f97316' });
}

How it works

  • DEG_TO_RAD is a predefined macro that converts degrees to radians, the unit every rotation uses.
  • setRotation moves the entity and reports the change as a Transform event.
  • MaterialComponent is an abstract base: it finds the entity’s material of any kind (Standard, Physical, Basic…).
  • setProps changes only the props you pass.

Blink a light on and off every half second without setInterval, using delay.

Blinker.jx
#pragma lifecycle(startup)
let lit = true;
let light = null;
let brightness = 0;
function blink() {
lit = !lit;
light.setProps({ intensity: lit ? brightness : 0 });
delay(blink, 500);
}
function startup() {
light = self.parent.getComponent(PointLightComponent);
if (!light) {
log('Put this Behavior under a point light.');
return;
}
brightness = light.props.intensity;
delay(blink, 500);
}

How it works

  • blink is declared above startup, because a function must be declared before the code that calls it.
  • delay(blink, 500) schedules the next blink; each call schedules the following one.
  • Setting intensity to 0 darkens the light while keeping it in the scene, and the authored intensity brings it back. light.setEnabled(false) would also switch it off, taking the light out of the scene until it is enabled again.
  • When the script stops, its pending delay is cancelled for you.

A coin that spins, plays a pop animation when the player presses E nearby, tells every script about it, and then removes itself.

Coin.jx
#pragma slot(ref=pickupRange, type=Number, min=0.5, max=10, default=2)
#pragma lifecycle(startup, update)
const coinPos = new THREE.Vector3();
const eyePos = new THREE.Vector3();
let coin = null;
let taken = false;
async function collect() {
taken = true;
emit('coin:collected', { value: 1 });
await Tween.to(coin.scale, { x: 0, y: 0, z: 0 }, { duration: 0.3, ease: Ease.InBack });
destroy(coin);
}
function startup() {
coin = self.parent;
}
function update(dt) {
if (taken) return;
coin.rotation.y += M_PI * dt;
if (!camera) return;
coin.getWorldPosition(coinPos);
camera.getWorldPosition(eyePos);
const near = eyePos.distanceTo(coinPos) < pickupRange;
if (near && Input.keyboard.isKeyReleased(Key.E)) collect();
}

How it works

  • The pickupRange slot is an editor field; the script reads it as a variable. See Slots.
  • M_PI radians a second is half a turn per second.
  • camera is undefined until rendering starts, so update checks it before use.
  • The two THREE.Vector3 vectors are made once and reused every frame, and getWorldPosition compares positions in world space whatever the parents are.
  • Input.keyboard.isKeyReleased(Key.E) is true once per press.
  • emit tells any script listening on coin:collected; Tween animates the scale; destroy removes the coin, and its Behavior with it.
Wrong
let scene = findEntity('Level'); // does not compile: scene is a global
Right
const level = findEntity('Level');

Pick another name for your own variables. Globals are constants.

Wrong
setTimeout(() => emit('door/close'), 3000); // setTimeout is undefined
Right
delay(() => emit('door/close'), 3000);
Wrong
function startup() {
this.parent.rotation.y = 1; // this is undefined in strict mode
}
Right
function startup() {
self.parent.rotation.y = 1;
}
Wrong
const cam = camera; // may be undefined: rendering has not started yet
function update() {
log(cam.position.y);
}
Right
function update() {
if (camera) log(camera.position.y);
}

camera and audioListener are live: read them when you need them instead of keeping a copy.