Slots
Updated
A slot is a field a script shows in the editor, and the variable that holds its value. Slots separate what a script does from how it is tuned: the author writes the code once, and anyone placing the script in a scene sets its speed, its target or its colour in the editor without reading a line of code. The same script can then be reused with different values on different objects. This page covers #pragma slot, every slot type and option, enums, #pragma type records and Array lists, defaults and ranges, and how slots appear in the editor. Buttons and validation have a page of their own.
Before you start
Section titled “Before you start”- Behavior scripts: Behaviors,
selfand the script log. - Directives: how a
#pragmais written, quoted and unquoted values, multi-line pragmas. - Editor scripts: the editor code that buttons and validators call.
Declaring a slot
Section titled “Declaring a slot”#pragma slot(ref=speed, type=Slider, min=0, max=10, step=0.1, default=4, group="Movement")#pragma lifecycle(update)
function update(dt) { self.parent.rotation.y += speed * dt;}The pragma declares the variable speed on its own line: do not write a separate let speed;. Code below the pragma can read it straight away, top-level code included. In play, the variable holds the value saved in the editor, or the default.
Slot variables are ordinary let variables: a script may assign one, but that changes only its own copy, never the saved value. Only editor code saves a slot, through slot(ref).
| Type | Value in the script | Default |
|---|---|---|
Number |
A number | 0 |
Slider |
A number, edited with a slider | 0 |
Integer |
A whole number | 0 |
Boolean |
true or false |
false |
String |
Text, or null |
null |
Color |
An RGB integer, such as 0xff8800 |
0xffffff |
Dropdown |
The chosen item: a string or number, or a list of them with multiselect |
0 |
Vector2 |
A new THREE.Vector2 |
[0, 0] |
Vector3 |
A new THREE.Vector3 |
[0, 0, 0] |
Quaternion |
A new THREE. |
[0, 0, 0, 1] |
Object3D |
The object in the script’s scene with the saved name, or null |
null |
Button |
Its label | 'Button' |
A #pragma type record |
A plain object, one entry per field | the field defaults |
Array<T> |
A plain list | [] |
Vectors, quaternions, records and lists are new objects built from the saved value each time the script loads: changing them in code does not change the slot.
#pragma slot(ref=count, type=Integer, default=3, min=1, max=20)#pragma slot(ref=offset, type=Vector3, default=[0, 1.5, 0])#pragma slot(ref=tint, type=Color, default=0xff8800)#pragma slot(ref=target, type=Object3D)#pragma slot(ref=title, type=String, default="Welcome")#pragma lifecycle(startup)
function startup() { if (target) target.position.copy(offset); const material = self.parent.getComponent(MaterialComponent); if (material) material.setProps({ color: tint }); log(title, count);}Options
Section titled “Options”| Option | Types | What it does |
|---|---|---|
ref |
all | The variable’s name. Required. |
type |
all | The slot type. Required. |
default |
all but records | The starting value, and what the editor resets the slot to. |
label |
all | The text the editor shows. Defaults to ref in Title Case: moveSpeed shows as Move Speed. |
tooltip |
all | Extra help the editor shows, for example on hover. |
group |
all | The editor section the slot is listed under. |
enabled |
all | false shows the field read-only. Default true. |
visible |
all | false hides the slot. Default true. See Hidden slots. |
on_event |
all | An editor function that receives the slot’s events. See Buttons and events. |
on_validate |
all | An editor function that checks the slot’s value. See Validation. |
min, max, step |
Number, Slider, Integer, Vector2, Vector3, Quaternion |
The allowed range and the editor’s increment. On vectors they apply to every component. |
items |
Dropdown |
The choices: a list, or the name of a #pragma enum. |
multiselect |
Dropdown |
Allow several choices; the value is then a list. |
(those of T) |
Array<T> |
Apply to every item. |
Any other option is an error that lists the valid ones. A declaration sets default, never value: value= is an error, since value is the slot’s current value, which only the editor sets.
Ranges
Section titled “Ranges”Sliderusesmin=0,max=100,step=1unless you set them: a slider needs two ends.Number,Integer,Vector2,Vector3andQuaternionhave no range unless you set one. AnIntegerslot’sstepmust be a whole number.stepmust be greater than zero,mincannot exceedmax, and a numberdefaultmust lie between them. ASliderwithdefault=500and no range is an error:Slot speed: default 500 is outside 0 to 100: set min and max to include it.
Dropdowns
Section titled “Dropdowns”A Dropdown’s items is a list of strings or numbers. Its value is the chosen item:
#pragma slot(ref=quality, type=Dropdown, items=[Low, Medium, High], default=Medium)#pragma slot(ref=layers, type=Dropdown, items=[Ground, Water, Sky], multiselect=true, default=[Ground])
if (quality === 'High') log('high quality');if (layers.includes('Water')) log('water on');Quote items that contain spaces or commas: items=["Very low", "Low, fast"].
An enum is a set of named whole numbers. #pragma enum(ref=Name, [A, B, C]) defines one and declares Name as a frozen constant, { A: 0, B: 1, C: 2 }, usable anywhere in the script. A Dropdown with items=Name shows the member names and takes the chosen member’s number:
#pragma enum(ref=Mode, [Walk, Run, Fly])#pragma slot(ref=mode, type=Dropdown, items=Mode, default=Run)
if (mode === Mode.Fly) self.parent.position.y += 1;- Members count from 0, in order. A member can set its own value, in decimal, hex, binary or negative:
[Walk=0x2, Run=0x4, Fly=0x8]. A member without one continues from the previous value + 1, so[A, B=10, C]is 0, 10, 11. - Two members may not share a value, written out or counted on.
default=Runnames a member and stores its number. Withmultiselect,default=[Walk, Run].- Declare the enum above the slots that use it. Quote members that contain spaces:
["Very fast", Slow].
Records and arrays
Section titled “Records and arrays”A record is a named group of fields, like a small form. #pragma type defines one. A slot of that type edits one record, and Array<Name> edits a list of them:
#pragma type( ref = Wave, fields = { count = { type = Integer, min = 1, default = 3 }, delay = { type = Number, min = 0, default = 1, label = "Delay (s)" }, kind = { type = Dropdown, items = [Walker, Runner] }, path = Array<Vector3>, },)#pragma slot(ref=finalWave, type=Wave)#pragma slot(ref=waves, type=Array<Wave>)#pragma slot(ref=speeds, type=Array<Number>, min=0, max=5, default=[1, 2])#pragma lifecycle(startup)
function startup() { waves.forEach((wave, i) => log('wave', i + 1, wave.count, wave.kind, wave.path.length)); log('final', finalWave.count);}- A field is
name=Type, orname={ type=Type, option=value, … }. Fields takedefault,labelandtooltip, plusmin,maxandstepfor number and vector types, anditemsandmultiselectfor a Dropdown. - A field’s type is any slot type but
Button, or a list of one:Array<Vector3>. A record cannot hold another record, and a list cannot hold a list. - A field without a default takes its type’s. A Dropdown field without one starts on its first item.
- A record slot takes no
default=: its fields have them. AnArray<Record>slot starts empty. A list of plain values may list starting items withdefault=[…]. - Fields have no implicit range: only the
minandmaxyou write. - Declare the type above the slots that use it.
- When a type gains a field, saved records get its default. When it loses one, the stale entry is dropped.
The editor checks every item and field like a slot of its own, and names it in the message: Item 2: Count: Enter a value at least 1.
Buttons and validation
Section titled “Buttons and validation”A slot can also call editor code: a Button slot runs a function when it is pressed, any slot can report its changes with on_event, and on_validate checks a value before it is saved. They are covered in Editor scripts.
Hidden slots
Section titled “Hidden slots”visible=false hides a slot, and editor code can show or hide one with slot(ref).visible. A hidden slot is treated as if it were not there: the editor does not list it, it sends no events, and it is not checked, so it never blocks a handler or play. It keeps its value, its variable still exists, and it is checked again as soon as it is shown.
In the editor
Section titled “In the editor”The editor reads a script’s slots by inspecting its Behavior, without running the script:
- Each slot is a field of its type, labelled with its
label, with itstooltipas help. - Slots with the same
groupform one section. Sections appear in the order their first slot is declared, and ungrouped slots form their own section. enabled=falsefields are read-only. Hidden slots are left out.- A slot whose value fails a check shows the error under it.
- A record shows its fields, and a list shows rows you can add and remove.
XR Creator shows these fields in Properties, each with a matching control and a Reset to default: see Slots in XR Creator. The editor saves the values on the Behavior component. Resetting a slot brings back its default. A slot’s identity is its ref and type together: renaming a slot or changing its type starts it again from its default.
Examples
Section titled “Examples”1. A tunable spinner
Section titled “1. A tunable spinner”One slider is enough to make a script reusable.
#pragma slot(ref=speed, type=Slider, min=0, max=10, step=0.1, default=2, label="Speed (rad/s)")#pragma slot(ref=clockwise, type=Boolean, default=true)#pragma lifecycle(update)
function update(dt) { const direction = clockwise ? -1 : 1; self.parent.rotation.y += direction * speed * dt;}A top that spins at the speed of a Slider slot, in the direction of a Boolean slot: two editor fields the script reads as variables.
Watch the top spin. Download the project to change Speed and Clockwise in XR Creator.
How it works:
speedis a slider from 0 to 10; its label overrides the default “Speed”.clockwiseis a checkbox in the editor and atrue/falsevariable in the script.- Every copy of this Behavior can have its own values.
2. Follow a chosen object
Section titled “2. Follow a chosen object”An Object3D slot lets the author pick the target in the editor, and a Vector3 slot sets the offset.
#pragma slot(ref=target, type=Object3D, tooltip="The object to follow")#pragma slot(ref=offset, type=Vector3, default=[0, 2, -4], group="Placement")#pragma slot(ref=smoothing, type=Slider, min=0, max=20, default=5, group="Placement")#pragma lifecycle(startup, update)
const goal = new THREE.Vector3();let follower = null;
function startup() { follower = self.parent; if (!target) log('Follow: no target chosen');}
function update(dt) { if (!target) return; goal.copy(target.position).add(offset); follower.position.lerp(goal, Math.min(1, smoothing * dt)); follower.lookAt(target.position);}How it works:
targetis the object of the scene with the saved name, ornullwhen none is chosen; the script checks for it.offsetarrives as aTHREE.Vector3built from the saved[x, y, z].goalis created once at the top, soupdatedoes not allocate a new vector every frame.
3. A movement mode from an enum
Section titled “3. A movement mode from an enum”An enum gives readable names to the choices of a Dropdown.
#pragma enum(ref=Mode, [Walk, Run, Fly])#pragma slot(ref=mode, type=Dropdown, items=Mode, default=Walk)#pragma slot(ref=walkSpeed, type=Number, min=0, max=10, default=1.5)#pragma lifecycle(startup, update)
let body = null;
function speedFor(m) { if (m === Mode.Run) return walkSpeed * 2.5; if (m === Mode.Fly) return walkSpeed * 4; return walkSpeed;}
function startup() { body = self.parent; if (mode === Mode.Fly) body.position.y += 2;}
function update(dt) { body.position.z += speedFor(mode) * dt;}How it works:
#pragma enumdeclaresModeas{ Walk: 0, Run: 1, Fly: 2 }, and the Dropdown shows the three names.modeholds the chosen member’s number, compared withMode.RunandMode.Fly.speedForis declared above the hooks that call it.
4. Waves of enemies from a list of records
Section titled “4. Waves of enemies from a list of records”A realistic spawner: the author builds the waves in the editor as a list of records, and the script plays them in order.
#pragma type( ref = Wave, fields = { count = { type = Integer, min = 1, max = 50, default = 3 }, pause = { type = Number, min = 0, default = 5, label = "Pause after (s)" }, kind = { type = Dropdown, items = [Walker, Runner] }, },)#pragma slot(ref=waves, type=Array<Wave>)#pragma slot(ref=spread, type=Number, min=0, max=50, default=8)#pragma lifecycle(startup)
function wait(seconds) { return new Promise((done) => delay(done, seconds * 1000));}
function spawnWave(wave) { const template = wave.kind === 'Runner' ? 'Runner Template' : 'Walker Template'; for (let i = 0; i < wave.count; i++) { spawn(template, { position: { x: Random.range(-spread, spread), y: 0, z: Random.range(-spread, spread) }, enabled: true, }); }}
async function startup() { for (let i = 0; i < waves.length; i++) { log('Wave', i + 1, 'of', waves.length); spawnWave(waves[i]); emit('waves/started', { wave: i + 1 }); await wait(waves[i].pause); } emit('waves/done');}How it works:
#pragma typedefines theWaverecord;Array<Wave>lets the author add, remove and edit waves in the editor.- Each record arrives as a plain object:
wave.count,wave.pause,wave.kind. spawncopies the template entity named by the wave’s kind; the templates can be saved disabled, andenabled: trueswitches each copy on.waitwrapsdelayin a promise so theasyncstartupcan await the pause between waves.
Common mistakes
Section titled “Common mistakes”Declaring the variable again
Section titled “Declaring the variable again”The pragma already declares it.
#pragma slot(ref=speed, type=Number, default=2)let speed = 2; // error: speed is already declared#pragma slot(ref=speed, type=Number, default=2)A default outside the slider’s range
Section titled “A default outside the slider’s range”#pragma slot(ref=distance, type=Slider, default=500)#pragma slot(ref=distance, type=Slider, min=0, max=1000, default=500)Setting value in the pragma
Section titled “Setting value in the pragma”#pragma slot(ref=lives, type=Integer, value=3)#pragma slot(ref=lives, type=Integer, default=3)Expecting an assignment to save the slot
Section titled “Expecting an assignment to save the slot”Assigning a slot variable in play changes only the script’s copy. The next time the script loads, it has the saved value again. To keep state while playing, use an ordinary variable; to change the saved value, use slot(ref).value in editor code.
Forgetting to check an Object3D slot
Section titled “Forgetting to check an Object3D slot”An Object3D slot is null when nothing is chosen, or when no object of the scene has the saved name. Check it before use: if (!target) return;.