Editor scripts
Updated
Editor code is the part of a script that runs only in the editor: the functions behind its buttons, field changes and validators. It lets a script carry its own authoring tools, such as a button that rebuilds a layout, a preset menu that fills in other fields, or a tool that lines up the selected objects, without adding anything to what players download. This page covers #editor_begin … #editor_end regions, Button slots and slot events with on_event, validators with on_validate, whole #editor_only tool scripts, the Editor global for the selection and the viewport camera, slot(ref) for changing slots, and what editor code may not contain.
Before you start
Section titled “Before you start”- Slots: editor fields,
on_eventandon_validate. Editor code is what those options call. - Directives:
#editor_begin,#editor_endand#editor_onlyare bare directives.
Why editor code is separate
Section titled “Why editor code is separate”Editor code is compiled into an output of its own and is absent from the player: not commented out, not switched off, simply not there. A player never downloads, checks or runs it, so authoring tools cost the player nothing. Both outputs keep the source’s line numbers, so an error in either points at the line you wrote.
Editor code runs only when the editor asks for it:
- a slot with
on_eventis used: a Button pressed, a value changed, a field focused or left; - the editor inspects the script and runs its
on_validatefunctions.
It never runs on a timer or every frame, and play code never calls it.
Editor regions
Section titled “Editor regions”Put editor functions between #editor_begin and #editor_end. The rest of the script is ordinary play code:
#pragma slot(ref=speed, type=Slider, min=0, max=10, default=4, on_validate=checkSpeed)#pragma slot(ref=reset, type=Button, label="Reset speed", on_event=onReset)#pragma lifecycle(update)
function update(dt) { self.parent.rotation.y += speed * dt;}
#editor_beginfunction checkSpeed(value) { return value !== 0 || 'A speed of 0 stops the object: use at least 0.1.';}function onReset() { slot('speed').value = 4;}#editor_endA turntable spins at the speed of a Slider slot; in XR Creator, a validator rejects a speed of 0 and a Reset speed button sets it back to 4.
Watch the turntable spin. Download the project, set Speed to 0 and press Reset speed in XR Creator.
How it works:
update, above the region, is play code: it spins the parent at the saved speed.on_validate=checkSpeedshows the message under the field when the speed is 0. See Validation.- Pressing the Reset speed button calls
onReset, which saves a new value throughslot('speed'). See Buttons and events. - The region between
#editor_beginand#editor_endis absent from play: players never download it.
A region holds plain JavaScript only:
- No directives inside.
#define,#if,#pragmaand every other directive is an error in a region. Declare slots above it, and put conditions around the whole region. - No substitutions. Constants and macros, your own and the predefined ones (
M_PI,DEG_TO_RAD,ASSERT), are not applied in a region. UseMath.PIand plain functions. - Only its own code. The editor output holds the region’s code, the slot variables, the script’s enums and its URL imports. Functions and variables declared in play code are not there: declare what the handlers need inside the region.
- A script may have several regions. Each needs its
#editor_end.
Buttons and events
Section titled “Buttons and events”A Button slot is a button in the editor. on_event names the function it calls, which must be declared in editor code, in a region or an editor-only script:
#pragma slot(ref=density, type=Slider, min=1, max=64, default=8, on_event=onDensity)#pragma slot(ref=rebuild, type=Button, label="Rebuild", on_event=onRebuild)
#editor_beginfunction onRebuild(event) { log('rebuilding at density', density);}function onDensity(event) { log('density is now', event.value);}#editor_endThe handler receives { type, ref, value }:
type |
Sent when |
|---|---|
click |
A Button is pressed. Only a Button sends it. |
change |
The slot’s value is committed, a Dropdown choice included. |
focus, blur |
The field gains or loses focus, for scripts that preview a value while it is edited. |
ref is the slot’s ref, and value its current value, or the new one for a change. Any slot type can have an on_event, not only a Button. A disabled or hidden slot sends nothing.
on_event without an editor region, or naming a function the region does not declare, is an error.
Validation
Section titled “Validation”on_validate names an editor function that checks a slot’s value. It returns true when the value is valid, false when it is not, or a message saying what is wrong:
#pragma slot(ref=code, type=String, default="ABC", on_validate=checkCode)
#editor_beginfunction checkCode(value) { return /^[A-Z]+$/.test(value) || 'Capital letters only.';}#editor_end- The editor runs every validator each time it inspects the script, and shows a failure under the field: the message,
Invalid value.forfalse, or a description when the validator throws or returns anything else. - A value that already fails the built-in checks (type, range, items) is not passed to the validator.
- There is no
patternoption: test a regular expression in a validator, as above. - A validator can read other slots through
slot(ref)but cannot change them. - Validators run only in the editor, never in play.
Editor-only scripts
Section titled “Editor-only scripts”A script whose first directive is #editor_only is an editor tool. All of its code is editor code, as if the whole file were one region, and it never runs in play:
// Row tool: lines the selected entities up along x#editor_only#define START_X 0#pragma slot(ref=spacing, type=Number, default=2, min=0.1, max=20, on_validate=checkSpacing)#pragma slot(ref=align, type=Button, label="Line up selection", on_event=onAlign)
function checkSpacing(value) { return value <= 10 || 'Keep the spacing at 10 or less, so the row stays in view.';}
function onAlign() { const selected = Editor.selection(); if (selected.length < 2) return log('Select at least two entities.'); selected.forEach((entity, i) => entity.position.set(START_X + i * spacing, entity.position.y, 0));}- Only blank lines and comments may come before
#editor_only. - Unlike a region, an editor-only script takes directives:
#define,#if,#pragma slot,#pragma enum,#pragma typeand#pragma import(Name="url")all work, and constants and macros are substituted in its code. - Slot variables hold the slot’s value when the code runs. Assigning one does not save it: use
slot('ref').value = …. - The editor reports the script as editor-only, and play skips it without an error.
What editor code can use
Section titled “What editor code can use”Editor code sees the same globals as play code, with these differences:
| Name | In editor code |
|---|---|
self |
The Behavior’s entity, in the scene being edited. |
scene |
The scene being edited that holds it. |
| Slot variables | The slots’ saved values. A handler gets a changed value in event.value. |
slot(ref) |
A live handle to any slot of the script. Editor code only. |
Editor |
The selection and the viewport camera. Editor code only. |
Scenes.load, Scenes.unload |
Throw: they would change the scene being edited. list, active and find work. |
Each event runs the editor code afresh, then calls the handler. Variables do not carry over from one click to the next, and whatever the handler takes (on listeners, delay timers, tweens) is released when it returns. A handler may be async: it is awaited.
Changing slots from editor code
Section titled “Changing slots from editor code”slot('ref') returns a live handle to one of the script’s slots, so one slot’s handler can change another:
| Property | Can you assign it? |
|---|---|
label, tooltip, group |
Yes |
value |
Yes: saves a new value |
enabled, visible |
Yes |
min, max, step |
Yes |
items, multiselect |
Yes |
ref, type, default, on_event, on_validate |
No: fixed by the pragma, assigning them throws |
- Reading a property returns a copy. To change a list or a record, assign a whole new value:
slot('waves').value = [...waves, { count: 5 }]. A partial record is filled in with the field defaults. - The handler sees its changes straight away. They are checked together, against the ranges, items and validators, and saved on the Behavior once the handler returns. If the handler throws, or a changed slot ends up invalid, nothing is saved.
- Inside a validator,
slot(ref)is read-only. slotcannot be used as a slotref, and play code cannot callslot().
The Editor global
Section titled “The Editor global”| Member | What it does |
|---|---|
Editor. |
The selected entities, in selection order: a new array each call. |
Editor. |
Select one entity. |
Editor. |
Select several. |
Editor. |
Clear the selection. |
Editor.camera |
The viewport camera. |
Editor.select accepts only entities in the scenes being edited, and throws on anything else, undefined included. Guard an empty selection before you pass its first entry on. In play, every Editor member throws.
Forbidden in editor code
Section titled “Forbidden in editor code”| Where | Not allowed | Why |
|---|---|---|
#editor_begin region |
Any directive, #editor_begin again |
A region is plain code; directives go around it. |
#editor_only script |
#editor_begin, #editor_end |
The whole script is already editor code. |
#editor_only script |
#pragma lifecycle |
Editor code runs only on slot events and validation. |
#editor_only script |
#pragma export |
Play scripts would find nothing, and an editor export could block the real one. |
#editor_only script |
#pragma import(name) without a URL |
Other scripts’ exports do not exist in the editor. |
#editor_only script |
#pragma dont_ |
It never runs in play. |
An #pragma import(name) of another script’s export in a script with a region is allowed, but in editor code its value is undefined: play scripts do not run in the editor. URL imports work in both. See Modules and Dynamic imports.
Examples
Section titled “Examples”1. A preset menu that fills in other fields
Section titled “1. A preset menu that fills in other fields”One Dropdown changes the range, value and label of another slot.
#pragma slot(ref=preset, type=Dropdown, items=[Calm, Storm], default=Calm, on_event=onPreset)#pragma slot(ref=wind, type=Slider, min=0, max=10, default=1)#pragma lifecycle(update)
function update(dt, time) { self.parent.rotation.z = Math.sin(time * wind) * 0.05;}
#editor_beginfunction onPreset(event) { if (event.type !== 'change') return; const storm = event.value === 'Storm'; slot('wind').max = storm ? 50 : 10; slot('wind').value = storm ? 30 : 1; slot('wind').label = storm ? 'Wind (storm)' : 'Wind';}#editor_endA sign sways with the Wind slot in play; in XR Creator, a Calm or Storm preset sets the wind field's range, value and label.
Watch the sign sway gently. Download the project and pick Storm in the Preset menu in XR Creator to see the Wind field change.
How it works:
- The play code above the region sways the parent with the saved
windvalue. onPresetreceives every event of thepresetslot; it acts only onchange.- The three assignments are checked together and saved when the handler returns, so
maxis raised beforevalueis checked.
2. Measure the selection
Section titled “2. Measure the selection”An editor-only tool that reports how far the selected entity is from the viewport camera.
#editor_only#pragma slot(ref=measure, type=Button, label="Measure selection", on_event=onMeasure)
function onMeasure() { const [first] = Editor.selection(); if (!first) return log('Nothing is selected.'); const distance = first.position.distanceTo(Editor.camera.position); log(first.name, 'is', distance.toFixed(1), 'm from the camera');}An #editor_only tool: select an entity in XR Creator and press Measure selection to log how far it is from the viewport camera.
Nothing happens in play: this script is a tool. Download the project, select a pillar in XR Creator and press Measure selection.
How it works:
#editor_onlymakes the whole file editor code; it never runs in play.Editor.selection()returns a new array; destructuring takes its first entry, orundefined.Editor.camerais the viewport camera, a camera object with aposition.- The entity’s
positionis relative to its parent; for an entity at the top of the scene, that is its place in the world.
3. Select every lamp
Section titled “3. Select every lamp”A tool that walks the edited scene and selects the entities whose name contains a word.
#editor_only#pragma slot(ref=word, type=String, default="Lamp", on_validate=checkWord)#pragma slot(ref=run, type=Button, label="Select matching", on_event=onSelect)
function checkWord(value) { return (value != null && value.trim().length > 0) || 'Type part of a name.';}
function onSelect() { const found = []; scene.traverse((object) => { if (isEntity(object) && object.name.includes(word)) found.push(object); }); Editor.select(found); log('Selected', found.length, 'entities matching', word);}An #editor_only tool: press Select matching in XR Creator to select every entity whose name contains the word typed in its field, Lamp by default.
Nothing happens in play: this script is a tool. Download the project and press Select matching in XR Creator to select the three lamps.
How it works:
checkWordkeeps the field from being empty; the editor shows the message under it.sceneis the scene being edited.scene.traversevisits every object, andisEntitykeeps only entities.Editor.select(found)replaces the selection; an empty array clears it.
4. Scatter the selection
Section titled “4. Scatter the selection”A realistic level-design tool: it spreads the selected objects randomly on a disc and turns each one, with a seed so the result can be repeated.
#editor_only#pragma slot(ref=radius, type=Slider, min=0.5, max=50, step=0.5, default=10, group="Scatter")#pragma slot(ref=randomTurn, type=Boolean, default=true, group="Scatter")#pragma slot(ref=seed, type=String, default="forest-1", group="Scatter")#pragma slot(ref=scatter, type=Button, label="Scatter selection", on_event=onScatter)#pragma slot(ref=gather, type=Button, label="Gather at origin", on_event=onGather)
function onScatter() { const selected = Editor.selection(); if (selected.length === 0) return log('Select the entities to scatter.'); const random = Random.seeded(seed); selected.forEach((entity) => { const angle = random.range(0, M_TAU); const distance = Math.sqrt(random.value()) * radius; entity.setPosition(Math.cos(angle) * distance, entity.position.y, Math.sin(angle) * distance); if (randomTurn) entity.setRotation(0, random.range(0, M_TAU), 0); }); log('Scattered', selected.length, 'entities');}
function onGather() { Editor.selection().forEach((entity) => entity.setPosition(0, entity.position.y, 0));}An #editor_only level-design tool: select the trees in XR Creator and press Scatter selection to spread and turn them on a disc, repeatably from a seed.
Nothing moves in play: this script is a tool. Download the project, select the trees in XR Creator and press Scatter selection, then Gather at origin.
How it works:
- Being
#editor_only, the script may use predefined constants such asM_TAU; an editor region could not. Random.seeded(seed)gives the same positions for the same seed, so a layout can be reproduced.setPositionandsetRotationmove each entity together with its physics colliders and report the change.
Common mistakes
Section titled “Common mistakes”Calling play code from a region
Section titled “Calling play code from a region”Functions declared in play code do not exist in the editor output.
function rebuild() { log('rebuilding'); }
#editor_beginfunction onRebuild() { rebuild(); // not defined in editor code}#editor_end#editor_beginfunction rebuild() { log('rebuilding'); }function onRebuild() { rebuild();}#editor_endUsing a directive or a constant inside a region
Section titled “Using a directive or a constant inside a region”#editor_beginfunction onTurn() { self.parent.rotation.y = M_HALF_PI; // not substituted in a region}#editor_end#editor_beginfunction onTurn() { self.parent.rotation.y = Math.PI / 2;}#editor_endAssigning a slot variable to save it
Section titled “Assigning a slot variable to save it”#editor_beginfunction onReset() { speed = 0; // changes a copy, nothing is saved}#editor_end#editor_beginfunction onReset() { slot('speed').value = 0;}#editor_endPassing an empty selection to Editor.select
Section titled “Passing an empty selection to Editor.select”Editor.select(undefined) throws. Check the selection first: const [first] = Editor.selection(); if (!first) return;. Call Editor.select() with no argument to clear it.
Keeping state between clicks
Section titled “Keeping state between clicks”Each event runs the editor code afresh, so a top-level let clicks = 0 is back to 0 on every click. Keep what must last in a slot, through slot(ref).value.