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.
Before you start
Section titled “Before you start”- A Behavior script is JavaScript attached to an entity. Read Behavior scripts if you have not written one yet.
- Hooks such as
startupandupdateare declared with#pragma lifecycle(...). See Lifecycle hooks. - The complete, generated list of globals with their full descriptions is in the Globals reference.
How globals work
Section titled “How globals work”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, XMLHttp |
HttpRequest |
Data and utilities |
window., 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.
Scene and entities
Section titled “Scene and entities”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.
| Global | What it is |
|---|---|
self | The entity the Behavior is on: self.position, self.getComponent(...). Its own Behavior is self.getComponent(BehaviorComponent). |
scene | The 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. |
findEntity | Find an entity in the current scene by id, a map read fine every frame, or else by name among its entities. |
findObject | Find 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. |
spawn | Copy an entity already in the scene (by name, or the entity itself) and add the copy with options. |
destroy | Same as scene.destroy: remove an entity (or id) and its subtree, disposing them and stopping their scripts. |
isEntity | Whether an object is an Entity, and so has components. |
camera | The camera the player sees through |
audioListener | Shared listener attached to the active camera; live, undefined until rendering starts. |
CameraDirector | Cut between cameras by name or id: switchTo(name), switchToMain(); current and main are the camera entities. |
Environment | Project 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).
| Global | What it is |
|---|---|
Scenes | Switch scenes: await Scenes.load(id), load(id, { additive: true }), unload(id), list(), active(). |
Editor | Editor tools only (#editor_only, #editor_begin): selection(), select(entities), camera. Throws in play. |
Signals and events
Section titled “Signals and events”Signals are named messages that scripts and components send to each other. See Events and signals.
| Global | What it is |
|---|---|
emit | Raise a signal, with optional data, for every script and the app. |
on | Call callback(data) right away each time signal is emitted; returns a function that stops it. Released with the script. |
once | Call callback(data) the next time signal is emitted, then stop; returns a function that stops it sooner. Released with the script. |
off | Stop every listener this script added with on or once for signal; other scripts keep theirs. |
EventType | Every event type a script can hear, by who sends it: compare them rather than typing the strings. |
Time and animation
Section titled “Time and animation”These globals schedule code and animate values. See Time and tweens.
| Global | What it is |
|---|---|
Time | Measure with Time.now(), Time.since(start); game time: Time.scale, pause(), resume(), isPaused(). |
Tween | Animate any object's numbers: Tween.to(mesh.position, { x: 5 }, { duration: 1 }), from, value, stop; awaitable. |
Ease | The 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, ... |
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. |
Input and the device
Section titled “Input and the device”Keyboard, mouse, touch, XR controllers, sensors and facts about the device. These are covered in Input and interaction.
| Global | What it is |
|---|---|
Input | Every input device: keyboard, mouse, touch, XR, accelerometer, gyroscope, microphone, device camera, location. |
Key | Defines the values for standard keys |
MouseButton | The MouseButton enum provides constants representing the different mouse buttons. |
Device | Platform facts for scripts that adapt to the device they run on. |
Torch | The phone's torch, by its back camera: await Torch.on(), off(), toggle(), isOn(). |
Haptics | Vibration on whatever the player has: XR controllers in an XR session, a gamepad's rumble when one is connected, the phone otherwise. |
WebBrowser | Read the browser location and open new tabs. |
XRButton names the buttons of an XR controller (XRButton.Trigger, XRButton.Squeeze, XRButton.A…). See XR.
Picking and space
Section titled “Picking and space”Rays and coordinate conversions, covered in Input and interaction.
| Global | What it is |
|---|---|
GraphicsRaycaster | A 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. |
PhysicsRaycaster | A 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. |
XRRaycaster | A 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: |
CoordinateSpace | Conversions between the screen, the world, and an object's own space. |
Networking
Section titled “Networking”Shared rooms where entities replicate between visitors. See Multiplayer.
| Global | What it is |
|---|---|
Network | Replicate 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. |
NetworkTraitType | Every trait a Networkable can replicate: traits: [NetworkTraitType.Transform, NetworkTraitType.PointLight]. |
NetworkCommand | Every command the room server defines: Network.command(NetworkCommand.ReactionSend, { reaction: '👍' }). |
Notifications
Section titled “Notifications”Toasts and dialogs shown from a script. See Notifications.
| Global | What it is |
|---|---|
NotificationService | Notifications, 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. |
NotificationType | The built-in notifications: Info, Success, Warning, Error, Compact. |
Data and utilities
Section titled “Data and utilities”HTTP, canvases, random numbers, pools, shared objects, streams, fonts, THREE and logging. See Data and utilities and Modules.
| Global | What it is |
|---|---|
HttpRequest | HTTP requests, cancelled when the script is released: get, post, …, request, and extend for a client with its own defaults. |
SURL | Route a URL through the configured CORS proxy. Exposed to scripts as SURL. |
Canvas | Canvases for scripts that draw their own images: labels, minimaps, dynamic textures. |
Random | The shared generator scripts use as Random: every method, with examples, is on RandomGenerator. Frozen, so no script can change it for the others. |
ObjectPool | Reuses objects instead of creating and discarding them, for things that come and go often: bullets, particles, floating damage numbers. |
Singleton | Named shared instances for this app: Singleton.get(key, factory), then Singleton.key. |
Streams | Live 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. |
Fonts | The app's font families: await Fonts.register(family, url, { weight, label }) for this session, unregister, has(family), families. |
THREE | Raw three.js in a Behavior: meshes, materials, vectors, colours and math. |
log | Write values to the script log. |
console | The app logger, with the usual console methods. |
Logger | The app logger: log, info, warn, error. Also reachable as console. |
ShaderPreset lists and registers the shader presets a Shader Material can draw. See Graphics.
Constants and macros
Section titled “Constants and macros”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.
| Global | What it is |
|---|---|
M_PI | π, half a turn in radians. |
M_TAU | 2π, a full turn in radians. |
M_HALF_PI | π/2, a quarter turn in radians. |
EPSILON | Float tolerance for positions and angles (1e-6). |
MAX_INT | Largest safe integer (Number.MAX_SAFE_INTEGER). |
MIN_INT | Smallest safe integer (Number.MIN_SAFE_INTEGER). |
SCRIPTING_RUNTIME_VERSION | Version number of the scripting runtime. |
DEG_TO_RAD | Convert degrees to radians. |
RAD_TO_DEG | Convert radians to degrees. |
ASSERT | Throw 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.
Component and entity classes
Section titled “Component and entity classes”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. |
The component of that class, or undefined. Also accepts the type string, such as 'comp-. |
entity. |
Every component of that class, for types an entity can hold several of (colliders, Signal Emitters). A new array each call. |
entity. |
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 |
|---|---|
Material |
get returns the entity’s material, whichever kind it is. |
Physics |
get lists every collider shape. |
Model |
get is the model’s source, whatever its format. |
Dynamic |
get 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.
Standard library
Section titled “Standard library”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.
Examples
Section titled “Examples”1. Read the basics
Section titled “1. Read the basics”A first look at the most common globals: the script’s own Behavior, its entity and its scene.
#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
selfis the entity the script’s Behavior is on.self.parentis the object the Behavior entity sits under: a common way to drive one object from a script.scene.entitiesis aMapof every entity in the scene, by id.logwrites to the script log, andSCRIPTING_RUNTIME_VERSIONis a constant the preprocessor fills in.
2. Use components and constants
Section titled “2. Use components and constants”Turn the parent a quarter turn in degrees and tint its material, whatever kind of material it has.
#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_RADis a predefined macro that converts degrees to radians, the unit every rotation uses.setRotationmoves the entity and reports the change as a Transform event.MaterialComponentis an abstract base: it finds the entity’s material of any kind (Standard, Physical, Basic…).setPropschanges only the props you pass.
3. Replace browser timers
Section titled “3. Replace browser timers”Blink a light on and off every half second without setInterval, using delay.
#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);}A point light switched on and off every half second by a script that schedules itself with delay instead of setInterval.
Watch the lamp blink. Drag to orbit the camera, scroll to zoom.
How it works
blinkis declared abovestartup, 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
intensityto 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
delayis cancelled for you.
4. Combine several globals
Section titled “4. Combine several globals”A coin that spins, plays a pop animation when the player presses E nearby, tells every script about it, and then removes itself.
#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
pickupRangeslot is an editor field; the script reads it as a variable. See Slots. M_PIradians a second is half a turn per second.cameraisundefineduntil rendering starts, soupdatechecks it before use.- The two
THREE.Vector3vectors are made once and reused every frame, andgetWorldPositioncompares positions in world space whatever the parents are. Input.keyboard.isKeyReleased(Key.E)is true once per press.emittells any script listening oncoin:collected;Tweenanimates the scale;destroyremoves the coin, and its Behavior with it.
Common mistakes
Section titled “Common mistakes”Assigning or redeclaring a global
Section titled “Assigning or redeclaring a global”let scene = findEntity('Level'); // does not compile: scene is a globalconst level = findEntity('Level');Pick another name for your own variables. Globals are constants.
Using browser timers
Section titled “Using browser timers”setTimeout(() => emit('door/close'), 3000); // setTimeout is undefineddelay(() => emit('door/close'), 3000);Using this instead of self
Section titled “Using this instead of self”function startup() { this.parent.rotation.y = 1; // this is undefined in strict mode}function startup() { self.parent.rotation.y = 1;}Reading camera too early
Section titled “Reading camera too early”const cam = camera; // may be undefined: rendering has not started yet
function update() { log(cam.position.y);}function update() { if (camera) log(camera.position.y);}camera and audioListener are live: read them when you need them instead of keeping a copy.