Skip to content

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.

This is what you will build, running in your browser:

Press Run example, then click the box. Each click picks a new colour and writes Box clicked to the script log below the scene.

You need:

  • A project open in XR Creator, with a scene. Create your first world shows how.
  • A little JavaScript: variables, functions, if and 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).

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

  2. Add a Behavior entity. A Behavior entity holds a script; it draws nothing itself.

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

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

Replace the code with this script:

Spinner.jx
#pragma lifecycle(startup, update)
const SPEED = 1; // radians a second
let 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 = 1 is 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 = null is declared at the top level, outside any function, so both hooks can use it. Scripts declare variables with let or const, never var.
  • self is the Behavior entity the script runs on. Its parent is the box, because you placed the Behavior under it in step 1.
  • startup runs once. It finds the box and keeps it, so update does not look it up again every frame.
  • update(dt) runs every frame. dt is the time since the last frame, in seconds. Adding SPEED * dt each frame turns the box at the same speed on a fast computer and on a slow phone.

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:

Spinner.jx
#pragma lifecycle(startup, update)
const SPEED = 1; // radians a second
let 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.

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.

  1. Select Box and add a Selectable component. A Selectable makes its entity clickable with a mouse, a touch or an XR controller, and reports Selectable::select when it is selected.

  2. Add a Signal Emitter component to Box and set its signal to box/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.

  3. Update the script:

    Spinner.jx
    #pragma lifecycle(startup, update)
    const SPEED = 1; // radians a second
    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;
    }
  4. 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) calls onBoxEvent each time something is sent on the signal box/clicked. Call it once, in startup: every call adds another listener.
  • event describes what happened: event.entityId is the entity, event.eventType the kind of event, such as 'Selectable::select', and event.data its details.
  • EventType.Selectable.Select is 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 of onBoxEvent ignores everything but a select.
  • Random.color() returns a random colour; getHexString() gives it as hex digits such as ff8800.
  • getComponent(StandardMaterialComponent) returns the box’s material component, and setProps changes its color prop. Component classes such as StandardMaterialComponent are globals.
  • setSelected(false) deselects the box straight away, so the next click selects it again and sends another Selectable::select.
  • onBoxEvent is declared above startup, which uses it. Scripts must declare a function before the code that calls it.

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:

Spinner.jx
#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=speed declares the variable speed. Do not write let speed as well: the pragma declares it.
  • type=Slider, min, max and step choose the editor control and its range. default is the value until you change it.
  • group puts the field under a heading. The label, Speed, comes from the ref in title case.
  • In play, speed holds the value saved in the editor. See Slots for every slot type.

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.

This script makes the box jump and land when Space is pressed.

Hopper.jx
#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) is true for one frame each time Space is let go, so one press makes one hop.
  • Tween.to animates numbers over time: here the box’s position.y, up to baseY + height in a quarter of a second.
  • repeat: 1 with yoyo: true plays the animation once more, backwards, so the box comes back down.
  • baseY is read once in startup, so a hop started mid-air still lands where the box began.

Each click switches the spin on or off.

ToggleSpin.jx
#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:

  • spinning is 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. update reads it every frame and returns early while it is false.

A click makes the box grow quickly and settle back, waiting for each step to finish before the next.

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

How it works:

  • pop is an async function, so it can await each tween: the shrink starts only once the growth has finished.
  • Ease.OutBack overshoots a little before settling, which gives the pop its bounce.
  • The popping flag ignores clicks while an animation is already running.

After five clicks, the box stops reacting and raises a signal other scripts can listen to.

ClickCounter.jx
#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:

  • on returns 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 with on('game/won', …), for example to show a message.
  • goal is an Integer slot, so the editor only accepts whole numbers from 1 to 20.

A function the #pragma lifecycle line does not name is never called by the engine. This update never runs:

Wrong
#pragma lifecycle(startup)
function update(dt) {
self.parent.rotation.y += dt;
}
Right
#pragma lifecycle(update)
function update(dt) {
self.parent.rotation.y += dt;
}

A fixed step turns the box faster on a fast screen and slower on a slow one. Multiply by dt:

Wrong
function update() {
box.rotation.y += 0.02;
}
Right
function update(dt) {
box.rotation.y += 1.2 * dt; // 1.2 radians a second on every device
}