Skip to content

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.

  • Slots: editor fields, on_event and on_validate. Editor code is what those options call.
  • Directives: #editor_begin, #editor_end and #editor_only are bare directives.

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_event is used: a Button pressed, a value changed, a field focused or left;
  • the editor inspects the script and runs its on_validate functions.

It never runs on a timer or every frame, and play code never calls it.

Put editor functions between #editor_begin and #editor_end. The rest of the script is ordinary play code:

ResettableSpeed.jx
#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_begin
function checkSpeed(value) {
return value !== 0 || 'A speed of 0 stops the object: use at least 0.1.';
}
function onReset() {
slot('speed').value = 4;
}
#editor_end

How it works:

  • update, above the region, is play code: it spins the parent at the saved speed.
  • on_validate=checkSpeed shows the message under the field when the speed is 0. See Validation.
  • Pressing the Reset speed button calls onReset, which saves a new value through slot('speed'). See Buttons and events.
  • The region between #editor_begin and #editor_end is absent from play: players never download it.

A region holds plain JavaScript only:

  • No directives inside. #define, #if, #pragma and 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. Use Math.PI and 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.

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:

Rebuild.jx
#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_begin
function onRebuild(event) {
log('rebuilding at density', density);
}
function onDensity(event) {
log('density is now', event.value);
}
#editor_end

The 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.

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:

Code.jx
#pragma slot(ref=code, type=String, default="ABC", on_validate=checkCode)
#editor_begin
function 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. for false, 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 pattern option: 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.

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:

RowTool.jx
// 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 type and #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.

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.

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.
  • slot cannot be used as a slot ref, and play code cannot call slot().
Member What it does
Editor.selection() The selected entities, in selection order: a new array each call.
Editor.select(entity) Select one entity.
Editor.select([a, b]) Select several.
Editor.select() 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.

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_unload() 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.

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.

Weather.jx
#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_begin
function 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_end

How it works:

  • The play code above the region sways the parent with the saved wind value.
  • onPreset receives every event of the preset slot; it acts only on change.
  • The three assignments are checked together and saved when the handler returns, so max is raised before value is checked.

An editor-only tool that reports how far the selected entity is from the viewport camera.

Measure.jx
#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');
}

How it works:

  • #editor_only makes the whole file editor code; it never runs in play.
  • Editor.selection() returns a new array; destructuring takes its first entry, or undefined.
  • Editor.camera is the viewport camera, a camera object with a position.
  • The entity’s position is relative to its parent; for an entity at the top of the scene, that is its place in the world.

A tool that walks the edited scene and selects the entities whose name contains a word.

SelectByName.jx
#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);
}

How it works:

  • checkWord keeps the field from being empty; the editor shows the message under it.
  • scene is the scene being edited. scene.traverse visits every object, and isEntity keeps only entities.
  • Editor.select(found) replaces the selection; an empty array clears it.

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.

Scatter.jx
#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));
}

How it works:

  • Being #editor_only, the script may use predefined constants such as M_TAU; an editor region could not.
  • Random.seeded(seed) gives the same positions for the same seed, so a layout can be reproduced.
  • setPosition and setRotation move each entity together with its physics colliders and report the change.

Functions declared in play code do not exist in the editor output.

Wrong
function rebuild() { log('rebuilding'); }
#editor_begin
function onRebuild() {
rebuild(); // not defined in editor code
}
#editor_end
Right
#editor_begin
function rebuild() { log('rebuilding'); }
function onRebuild() {
rebuild();
}
#editor_end

Using a directive or a constant inside a region

Section titled “Using a directive or a constant inside a region”
Wrong
#editor_begin
function onTurn() {
self.parent.rotation.y = M_HALF_PI; // not substituted in a region
}
#editor_end
Right
#editor_begin
function onTurn() {
self.parent.rotation.y = Math.PI / 2;
}
#editor_end
Wrong
#editor_begin
function onReset() {
speed = 0; // changes a copy, nothing is saved
}
#editor_end
Right
#editor_begin
function onReset() {
slot('speed').value = 0;
}
#editor_end

Passing 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.

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.