Write your first script
Updated
Worlds become interactive through Behavior scripts: short JavaScript programs attached to entities. In this tutorial you write a complete one, one small step at a time. By the end, a box spins on its own, takes a new colour each time someone clicks it, reports what happens in the script log, and has a speed you can tune in the editor without touching the code. Each step adds a few lines and explains what they do, so you finish knowing not only that the script works but why.
Try it
Section titled “Try it”This is what you will build, running in your browser:
A box that spins every frame and takes a new colour when you click it: a Behavior script, a Selectable and a Signal Emitter.
Click the box. Drag to orbit the camera, scroll to zoom.
Press Run example, then click the box. Each click picks a new colour and writes Box clicked to the script log below the scene.
Before you start
Section titled “Before you start”You need:
- A project open in XR Creator, with a scene. Create your first world shows how.
- A little JavaScript: variables, functions,
ifand arrow functions such as(event) => { … }. - An idea of what entities, components and Behaviors are. Each takes a few minutes to read.
You will meet these ideas along the way, each explained as it comes: hooks (functions the engine calls), self (the entity the script runs on), signals (named messages), Signal Emitter (the component that turns clicks into signals) and slots (editor fields for a script).
What you will build
Section titled “What you will build”| Step | The box… | You learn |
|---|---|---|
| 1 | exists, with a script under it | Behavior entities and self.parent |
| 2 | spins | The startup and update hooks, and frame time |
| 3 | reports what it does | log and the script log |
| 4 | changes colour when clicked | Selectable, Signal Emitter, on and EventType |
| 5 | has a speed you set in the editor | Slots |
Step 1: set up the scene
Section titled “Step 1: set up the scene”-
Add a box to the scene: a Primitive Mesh entity with a box shape. Name it
Box, and lift it a little so it sits above the floor. -
Add a Behavior entity. A Behavior entity holds a script; it draws nothing itself.
-
In the hierarchy, drag the Behavior entity onto
Box, so it becomes a child of the box. The script can now reach the box as its parent. -
Open the Behavior’s code. A new Behavior starts with this:
New Behavior #pragma lifecycle(startup,update,dispose)function startup() {}function update(delta,time) {}function dispose() {}
The first line is a directive: a line starting with # that the runtime reads before the script runs. #pragma lifecycle(...) lists the hooks the script has, the functions the engine calls for you:
| Hook | When the engine calls it |
|---|---|
startup() |
Once, when the script starts. |
update(delta, time) |
Every frame. delta is the seconds since the last frame; time the seconds the world has been playing. |
dispose() |
Once, when the script stops for good. |
Step 2: spin the box
Section titled “Step 2: spin the box”Replace the code with this script:
#pragma lifecycle(startup, update)
const SPEED = 1; // radians a secondlet box = null;
function startup() { box = self.parent;}
function update(dt) { box.rotation.y += SPEED * dt;}Press Play. The box turns steadily around its vertical axis.
What each part does:
#pragma lifecycle(startup, update)names only the two hooks this script uses. The engine calls only the hooks you list.const SPEED = 1is the turning speed. Angles in MIRA are in radians: a full turn is about 6.28 radians, so the box turns once every six seconds or so.let box = nullis declared at the top level, outside any function, so both hooks can use it. Scripts declare variables withletorconst, nevervar.selfis the Behavior entity the script runs on. Itsparentis the box, because you placed the Behavior under it in step 1.startupruns once. It finds the box and keeps it, soupdatedoes not look it up again every frame.update(dt)runs every frame.dtis the time since the last frame, in seconds. AddingSPEED * dteach frame turns the box at the same speed on a fast computer and on a slow phone.
Step 3: write to the log
Section titled “Step 3: write to the log”The script log shows what scripts write with log, and the errors that stop them. It is the first place to look when something does not work. Add a line to startup:
#pragma lifecycle(startup, update)
const SPEED = 1; // radians a secondlet box = null;
function startup() { box = self.parent; log('Spinning', box.name, 'at', SPEED, 'rad/s');}
function update(dt) { box.rotation.y += SPEED * dt;}Press Play again. The log shows Spinning Box at 1 rad/s.
log(...values)writes its values on one line, separated by spaces. It accepts strings, numbers, objects and entities.- Avoid logging in
update: it runs every frame, so the log would fill with dozens of lines a second.
Step 4: react to a click
Section titled “Step 4: react to a click”A click reaches a script in three hops: a component notices it, a Signal Emitter sends it on a named signal, and the script listens to that signal.
-
Select
Boxand add a Selectable component. A Selectable makes its entity clickable with a mouse, a touch or an XR controller, and reportsSelectable::selectwhen it is selected. -
Add a Signal Emitter component to
Boxand set its signal tobox/clicked. A component never talks to scripts directly: it hands its events to the Signal Emitters on its entity, and each emitter sends them on its signal. -
Update the script:
Spinner.jx #pragma lifecycle(startup, update)const SPEED = 1; // radians a secondlet box = null;function onBoxEvent(event) {if (event.eventType !== EventType.Selectable.Select) return;const color = '#' + Random.color().getHexString();box.getComponent(StandardMaterialComponent).setProps({ color: color });box.getComponent(SelectableComponent).setSelected(false);log('Box clicked, new colour', color);}function startup() {box = self.parent;on('box/clicked', onBoxEvent);log('Spinning', box.name, 'at', SPEED, 'rad/s');}function update(dt) {box.rotation.y += SPEED * dt;} -
Press Play and click the box. It takes a new colour, and the log says so.
What the new lines do:
on('box/clicked', onBoxEvent)callsonBoxEventeach time something is sent on the signalbox/clicked. Call it once, instartup: every call adds another listener.eventdescribes what happened:event.entityIdis the entity,event.eventTypethe kind of event, such as'Selectable::select', andevent.dataits details.EventType.Selectable.Selectis the constant for'Selectable::select'. Comparing against constants instead of typing strings protects you from typos.- The Signal Emitter forwards every event of the box, including
Selectable::deselect, so the first line ofonBoxEventignores everything but a select. Random.color()returns a random colour;getHexString()gives it as hex digits such asff8800.getComponent(StandardMaterialComponent)returns the box’s material component, andsetPropschanges itscolorprop. Component classes such asStandardMaterialComponentare globals.setSelected(false)deselects the box straight away, so the next click selects it again and sends anotherSelectable::select.onBoxEventis declared abovestartup, which uses it. Scripts must declare a function before the code that calls it.
Step 5: add an editor field
Section titled “Step 5: add an editor field”Hard-coding SPEED means editing the code to tune it. A slot turns a variable into a field in the editor, with a slider, a range and a default. Replace the SPEED constant with a slot:
#pragma slot(ref=speed, type=Slider, min=0, max=5, step=0.1, default=1, group="Spin")#pragma lifecycle(startup, update)
let box = null;
function onBoxEvent(event) { if (event.eventType !== EventType.Selectable.Select) return; const color = '#' + Random.color().getHexString(); box.getComponent(StandardMaterialComponent).setProps({ color: color }); box.getComponent(SelectableComponent).setSelected(false); log('Box clicked, new colour', color);}
function startup() { box = self.parent; on('box/clicked', onBoxEvent); log('Spinning', box.name, 'at', speed, 'rad/s');}
function update(dt) { box.rotation.y += speed * dt;}Select the Behavior in the editor: a Spin section now shows a Speed slider from 0 to 5. Set it to 3 and press Play.
ref=speeddeclares the variablespeed. Do not writelet speedas well: the pragma declares it.type=Slider,min,maxandstepchoose the editor control and its range.defaultis the value until you change it.groupputs the field under a heading. The label, Speed, comes from therefin title case.- In play,
speedholds the value saved in the editor. See Slots for every slot type.
Examples
Section titled “Examples”Each example builds on the box from this tutorial: a Box with a Selectable and a Signal Emitter on box/clicked, and the Behavior entity under it.
1. Hop when the player presses Space
Section titled “1. Hop when the player presses Space”This script makes the box jump and land when Space is pressed.
#pragma slot(ref=height, type=Number, min=0, max=3, default=1)#pragma lifecycle(startup, update)
let box = null;let baseY = 0;
function startup() { box = self.parent; baseY = box.position.y;}
function update() { if (Input.keyboard.isKeyReleased(Key.Space)) { Tween.to(box.position, { y: baseY + height }, { duration: 0.25, repeat: 1, yoyo: true }); }}How it works:
Input.keyboard.isKeyReleased(Key.Space)istruefor one frame each time Space is let go, so one press makes one hop.Tween.toanimates numbers over time: here the box’sposition.y, up tobaseY + heightin a quarter of a second.repeat: 1withyoyo: trueplays the animation once more, backwards, so the box comes back down.baseYis read once instartup, so a hop started mid-air still lands where the box began.
2. Start and stop the spin with a click
Section titled “2. Start and stop the spin with a click”Each click switches the spin on or off.
#pragma lifecycle(startup, update)
const SPEED = 2;let box = null;let spinning = true;
function onBoxEvent(event) { if (event.eventType !== EventType.Selectable.Select) return; spinning = !spinning; box.getComponent(SelectableComponent).setSelected(false); log(spinning ? 'Spinning again' : 'Stopped');}
function startup() { box = self.parent; on('box/clicked', onBoxEvent);}
function update(dt) { if (!spinning) return; box.rotation.y += SPEED * dt;}How it works:
spinningis a top-level variable, so its value is kept from frame to frame and shared by both functions.- The click handler only flips the flag.
updatereads it every frame and returns early while it isfalse.
3. Pop when clicked
Section titled “3. Pop when clicked”A click makes the box grow quickly and settle back, waiting for each step to finish before the next.
#pragma lifecycle(startup)
let box = null;let popping = false;
async function pop() { popping = true; await Tween.to(box.scale, { x: 1.4, y: 1.4, z: 1.4 }, { duration: 0.15, ease: Ease.OutQuad }); await Tween.to(box.scale, { x: 1, y: 1, z: 1 }, { duration: 0.4, ease: Ease.OutBack }); popping = false;}
function onBoxEvent(event) { if (event.eventType !== EventType.Selectable.Select) return; box.getComponent(SelectableComponent).setSelected(false); if (!popping) pop();}
function startup() { box = self.parent; on('box/clicked', onBoxEvent);}A box that grows and settles back with a bounce when clicked: two awaited Tweens on its scale, started from a Selectable event.
Click the box. Drag to orbit the camera, scroll to zoom.
How it works:
popis anasyncfunction, so it canawaiteach tween: the shrink starts only once the growth has finished.Ease.OutBackovershoots a little before settling, which gives the pop its bounce.- The
poppingflag ignores clicks while an animation is already running.
4. Count clicks and announce a winner
Section titled “4. Count clicks and announce a winner”After five clicks, the box stops reacting and raises a signal other scripts can listen to.
#pragma slot(ref=goal, type=Integer, min=1, max=20, default=5)#pragma lifecycle(startup)
let clicks = 0;let stopListening = null;
function onBoxEvent(event) { if (event.eventType !== EventType.Selectable.Select) return; self.parent.getComponent(SelectableComponent).setSelected(false); clicks += 1; log('Click', clicks, 'of', goal); if (clicks >= goal) { stopListening(); emit('game/won', { clicks: clicks }); }}
function startup() { stopListening = on('box/clicked', onBoxEvent);}How it works:
onreturns a function that stops the listener. Calling it once the goal is reached makes further clicks do nothing.emit('game/won', …)raises a signal of your own, with data. Any other script can react withon('game/won', …), for example to show a message.goalis anIntegerslot, so the editor only accepts whole numbers from 1 to 20.
Common mistakes
Section titled “Common mistakes”Forgetting to list a hook
Section titled “Forgetting to list a hook”A function the #pragma lifecycle line does not name is never called by the engine. This update never runs:
#pragma lifecycle(startup)
function update(dt) { self.parent.rotation.y += dt;}#pragma lifecycle(update)
function update(dt) { self.parent.rotation.y += dt;}Moving by a fixed amount each frame
Section titled “Moving by a fixed amount each frame”A fixed step turns the box faster on a fast screen and slower on a slow one. Multiply by dt:
function update() { box.rotation.y += 0.02;}function update(dt) { box.rotation.y += 1.2 * dt; // 1.2 radians a second on every device}