Directives
Updated
A directive is a line that starts with #. Directives are applied to the script’s source before the script runs, in a step called preprocessing. They let you name constants, write small macros, keep or drop code depending on the device, and declare things about the script that the runtime reads: its hooks, its editor fields, what it shares. This page covers the bare directives that decide which lines are compiled, the predefined constants, macros and device flags, and the list of #pragma directives with the page that documents each one.
Before you start
Section titled “Before you start”- Behavior scripts: how a script is preprocessed, checked, then run.
- Lifecycle hooks:
#pragma lifecycleis the directive almost every script has.
Bare directives and #pragma
Section titled “Bare directives and #pragma”There are two kinds of directive, by one rule:
- A bare directive acts on preprocessing itself. It decides which lines are compiled and which output they go to, or it reports while preprocessing:
#define,#if,#error,#editor_begin. - A
#pragmadeclares something about the script that the runtime reads: its hooks, its editor fields, what it shares.#pragma lifecycle,#pragma slot,#pragma export.
Every source line keeps its line number through preprocessing, so an error always points at the line you wrote. A directive may have spaces after the # (# define) and leading spaces before it. A # at the start of a line inside a template literal or a block comment is text, not a directive, and a class’s private member (#count = 0;) is code.
Bare directives
Section titled “Bare directives”| Directive | What it does |
|---|---|
#define NAME value |
A constant, substituted in the code. |
#define NAME(a, b) body |
A function-like macro. In the body, #a is the text of argument a as a string: #define SHOW(x) log(#x, x) makes SHOW(speed) log speed 4. |
#define NAME body \ |
A value or body continued on the next line, after a trailing \. |
#undef NAME |
Remove a definition. |
#if expr |
Compile the lines up to the next #elif, #else or #endif if expr is true. |
#ifdef NAME / #ifndef NAME |
Compile the lines if NAME is, or is not, defined. |
#elif expr |
Another branch of an #if. |
#else |
The branch taken when no other was. |
#endif |
End an #if, #ifdef or #ifndef block. |
#error message |
Stop the script with this message. |
#warning message |
Report this message as a warning in the browser console and carry on. |
#editor_begin / #editor_end |
The lines between are editor code, absent from play. See Editor scripts. |
#editor_only |
The whole script is editor code and never runs in play. See Editor scripts. |
Constants and macros
Section titled “Constants and macros”A constant gives a value a name; a macro is a small piece of code with parameters that the preprocessor pastes in where it is used. Both are replaced in the text before the script runs, so they cost nothing at run time.
#define SPEED 4#define GREETING "Hello"#define CLAMP(v, lo, hi) Math.min(Math.max(v, lo), hi)
#pragma lifecycle(update)
function update(dt) { self.parent.position.x = CLAMP(self.parent.position.x + SPEED * dt, -10, 10);}log(GREETING);- A constant’s value is the rest of the line, with any trailing
//comment removed. A//inside a quoted string, as in a URL, stays part of the value. - A name is substituted only as a whole word, never inside a string or comment, and never as a property name:
Number.EPSILONstays as written even thoughEPSILONis defined. - A macro’s arguments are substituted wherever its parameters appear in the body, inside strings too.
- Definitions are not substituted inside a
#pragma: writemax=8, notmax=MAX_SIZE. - Defining a name twice is an error.
#undefit first. - An
#editor_beginregion does not see definitions: write plain JavaScript there.
Conditions
Section titled “Conditions”Conditions keep or drop whole blocks of code. A dropped block is not compiled at all, so it may even use names that do not exist on the device.
#if IS_MOBILE || IS_HEADSETconst quality = 'low';#elif defined(IS_TOUCH)const quality = 'medium';#elseconst quality = 'high';#endif
#ifndef IS_XR_CAPABLE#warning this script is meant for XR#endif- An
#ifexpression compares literals: numbers, strings,true,false,null, with the usual operators (==,!=,<,>,<=,>=,&&,||,!,+,-,*,/,%,? :and parentheses). Defined names are substituted first, anddefined(NAME)is true whenNAMEis defined. - A name that is not defined reads as
0. So#if IS_HEADSETand#ifdef IS_HEADSETboth work on every device. - Blocks nest. Every
#ifneeds its#endif, and nothing may follow an#elsebut#endif. - A
#pragmacan sit inside an#ifblock, but an#ifcannot sit inside a multi-line#pragma: put the condition around the whole pragma.
Predefined constants
Section titled “Predefined constants”| Name | Value |
|---|---|
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 |
1e-6, a tolerance for positions and angles (Number. is far too small for them) |
MAX_INT, MIN_INT |
The largest and smallest safe integers |
SCRIPTING_ |
The scripting runtime’s version number |
__LINE__ |
The current source line number |
__FILE__ |
The name of the Behavior entity running the script, as a string |
__DATE__, __TIME__ |
The date and time the script was preprocessed, as strings in the device’s locale |
Predefined macros
Section titled “Predefined macros”| Macro | What it does |
|---|---|
DEG_TO_RAD(x) |
Degrees to radians. |
RAD_TO_DEG(x) |
Radians to degrees. |
ASSERT(x) |
Throws Assertion failed: x, with the text of x, when x == false. |
ASSERT compares with == false, so it throws for false, 0, '' and '0', but not for null or undefined. Test those explicitly: ASSERT(target != null).
Device flags
Section titled “Device flags”Each device preprocesses its scripts when it loads them, with flags describing that device. A flag is defined, as true, only where it holds; elsewhere it is undefined.
| Flag | Defined when |
|---|---|
IS_MOBILE |
The device is a phone or tablet. |
IS_TOUCH |
The device has a touch screen. |
IS_HEADSET |
The page runs in a headset’s own browser. |
IS_XR_CAPABLE |
The browser has the WebXR API. Desktop browsers can have it too: use await Device. for an exact answer. |
PLATFORM_, PLATFORM_, PLATFORM_, PLATFORM_, PLATFORM_IOS |
The operating system. One of them, at most. |
The same facts are available while the script runs, through the Device global: Device.isMobile(), Device.isTouch(), Device.isHeadset(), Device.hasWebXR(). Choose between them like this:
- A flag drops the other branch’s code entirely, so it costs nothing at run time. Use it for code that only makes sense on some devices.
Devicelets one build of the code decide later, for example after anawait.
#pragma directives
Section titled “#pragma directives”| Directive | What it does | Page |
|---|---|---|
#pragma lifecycle(startup, update, …) |
Declare the hooks the engine calls; hook=function uses another name. |
Lifecycle hooks |
#pragma slot(ref=…, type=…, …) |
Declare an editor field and the variable that holds its value. | Slots |
#pragma enum(ref=Name, [A, B=10, C]) |
Named integers, usable as Dropdown items. | Slots |
#pragma type(ref=Name, fields={ … }) |
A record type for slots. | Slots |
#pragma export(name) |
Publish a variable to other scripts. | Modules |
#pragma import(name) |
Read another script’s export. | Modules |
#pragma import(Name="https:// |
Load a module from a URL. | Dynamic imports |
#pragma dont_ |
Keep this entity when its scene is switched away. | Scene switching |
#pragma tool(name=…, description=…, …) |
Declare a tool an AI agent can call. Only in an AI tool script. | AI agents |
Shader sources for a Shader Material use their own pragmas in the same grammar; see Graphics.
Writing a pragma
Section titled “Writing a pragma”A pragma may span several lines, up to the ) that closes it, and may end with a trailing comma. // and /* */ comments may end its lines:
#pragma slot( ref = speed, // the variable type = Slider, min = 0, max = 10, label = "Speed (m/s)", group = "Movement",)Values follow two rules:
- Quoted, anything goes. A quoted value is taken literally and stays text:
default="5"is the string"5". It keeps any,,=,(or)inside it, in lists too:default=["a, b", "c)"]. Write a quote inside one as\"or\'. Every other backslash stays as written, so a pattern like"^\d+$"keeps its meaning. - Unquoted, kept as written up to the next
,or). Numbers become numbers (4,-2.5,0xff8800),true/yesandfalse/nobecome booleans,[a, b]becomes a list, and anything else is text:label=Speed (m/s)works. A comma or an unbalanced)would end the value early, so the error says to quote it.
Names a pragma writes into the code, such as a slot ref, a hook handler or an import name, must be valid JavaScript names.
Examples
Section titled “Examples”1. Constants instead of magic numbers
Section titled “1. Constants instead of magic numbers”Named constants make a script readable, and the preprocessor removes them before it runs.
#define RADIUS 3#define HEIGHT 1.5#define TURNS_PER_SECOND 0.25
#pragma lifecycle(update)
function update(dt, time) { const angle = time * TURNS_PER_SECOND * M_TAU; self.parent.position.set(Math.cos(angle) * RADIUS, HEIGHT, Math.sin(angle) * RADIUS);}A moon circling a planet, placed every frame from #define constants and the predefined M_TAU.
Watch the moon circle the planet. Drag to orbit the camera, scroll to zoom.
How it works:
RADIUS,HEIGHTandTURNS_PER_SECONDare replaced by their values as whole words.M_TAUis predefined: one full turn, soTURNS_PER_SECOND * M_TAUis the angle travelled each second.update(dt, time)places the parent on a circle from the playing time.
2. Lighter work on phones and headsets
Section titled “2. Lighter work on phones and headsets”Device flags drop the code a device does not need. Here a phone or headset spawns fewer decorations.
#if IS_MOBILE || IS_HEADSET#define COUNT 20#else#define COUNT 80#endif
#pragma lifecycle(startup)
function startup() { for (let i = 0; i < COUNT; i++) { spawn('Flower', { position: { x: Random.range(-10, 10), y: 0, z: Random.range(-10, 10) }, enabled: true, }); } log('Spawned', COUNT, 'flowers on', __FILE__);}How it works:
- The
#ifkeeps exactly one#define COUNT, chosen when the device loads the script. spawn('Flower', …)copies an entity namedFloweralready in the scene;enabled: trueswitches the copy on even when the template is saved disabled.__FILE__is replaced by the name of the Behavior entity, handy in log lines.
3. Debug-only logging with a macro
Section titled “3. Debug-only logging with a macro”A macro that logs an expression and its value, which you switch off in one line before publishing.
#define DEBUG 1
#if DEBUG#define TRACE(x) log(#x, '=', x)#else#define TRACE(x) undefined#endif
#pragma lifecycle(startup, update)
let target = null;
function startup() { target = findEntity('Player'); ASSERT(target != null) TRACE(target.name); TRACE(target.position.y.toFixed(2));}
function update(dt) { self.parent.lookAt(target.position);}How it works:
#xturns the macro’s argument into its own source text, so the first log readstarget.name = Player.- Setting
DEBUGto0makes everyTRACE(...)expand to a statement that does nothing, and the values are never computed. ASSERT(target != null)stops the script with a clear message if the scene has noPlayerentity.
4. Choosing at run time with Device
Section titled “4. Choosing at run time with Device”When the choice depends on something only known while running, use the Device global instead of a flag.
#pragma lifecycle(startup)
async function startup() { if (Device.isHeadset()) { log('Running in a headset browser'); return; } const vr = await Device.supportsImmersiveVR(); if (vr) log('This device can enter VR'); else if (Device.isTouch()) log('Touch controls'); else log('Mouse and keyboard controls');}How it works:
Device.isHeadset()andDevice.isTouch()answer at once.Device.supportsImmersiveVR()returns a promise, sostartupisasyncand awaits it.- One script handles every device, where flags would build a different script per device.
Common mistakes
Section titled “Common mistakes”Using a definition inside a #pragma
Section titled “Using a definition inside a #pragma”Definitions are not substituted inside pragmas.
#define MAX_SPEED 8#pragma slot(ref=speed, type=Slider, min=0, max=MAX_SPEED)#pragma slot(ref=speed, type=Slider, min=0, max=8)Expecting ASSERT to catch null
Section titled “Expecting ASSERT to catch null”const door = findEntity('Door');ASSERT(door) // does not throw when door is undefinedconst door = findEntity('Door');ASSERT(door != null)Defining a name twice
Section titled “Defining a name twice”#define SPEED 2#define SPEED 4#define SPEED 2#undef SPEED#define SPEED 4