Events and signals
Updated
A signal is a named message sent across the whole application. Any script can raise one with emit, and any script can listen for it with on or once. Components use the same channel: when a button is pressed, an object is clicked or two bodies collide, the component sends an event, and a Signal Emitter on its entity puts that event on a signal. An Enable on Signal component can switch things on and off when a signal arrives, without a line of code. Signals let parts of a world talk to each other without holding references to each other: the door does not need to know about the button, it only listens for door/open.
Before you start
Section titled “Before you start”- Scripts usually start listening in their
startuphook, declared with#pragma lifecycle(...). See Lifecycle hooks. - Components can be enabled and disabled. See Components.
The event bus
Section titled “The event bus”The event bus is one channel shared by the whole world. Anything put on it carries a signal: a name, any string you choose, such as door/open, ui:menu or score. Anything listening to that name receives it. Three kinds of traffic share the bus:
| Traffic | Put on the bus by | Example |
|---|---|---|
| Script signals | A script, with emit(signal, data) |
emit('coin', 10) |
| Component events | A Signal Emitter, on behalf of the components on its entity | A click on a box, on box/clicked |
| System signals | The runtime itself | Reserved names, such as Entity::grab; scripts cannot emit them |
Use a prefix to keep your signals apart and readable: lamp/selected, lamp/deselected, lamp/toggle.
Raising and receiving signals
Section titled “Raising and receiving signals”| Global | What it does |
|---|---|
emit(signal, data?) |
Raises signal with optional data, for every script and the app. |
on(signal, callback) |
Calls callback(data) right away, each time signal is emitted. Returns a function that stops listening. |
once(signal, callback) |
Calls callback(data) the next time signal is emitted, then stops. Returns a function that stops it sooner. |
off(signal) |
Stops every listener this script added with on or once for signal. Other scripts keep theirs. |
For a script signal, the callback receives what was passed to emit. For a component event, it receives the whole event (see Component events).
Only current listeners hear a signal. A signal raised before a script has called on is not heard by that script. When one script emits as it starts, give the others time to start listening first, for example with delay.
on and once are immediate. The callback runs inside emit, before emit returns. An error in the callback goes to the script log and does not reach the script that emitted, or the other listeners. An async callback works too.
Scripts hear a signal in execution order. When several scripts listen to the same signal, the script whose Behavior has the lowest executionIndex hears it first, and scripts with the same index hear it in the order they started listening. That holds however late a script starts listening, and a changed executionIndex applies from the next emit. See Lifecycle hooks for execution order.
Listeners stop by themselves. A script’s listeners are removed when the script stops: when its entity is destroyed, its Behavior is removed, its code changes or its scene unloads. To stop earlier, call the function on or once returns, or call off(signal) to stop all of this script’s listeners for that signal.
Reserved signals
Section titled “Reserved signals”The engine keeps a set of system signals for itself, such as Entity::grab, Scene::activating, Script::log and Notification::show. emit throws when a script tries to raise one. Pick your own names, with your own prefix, and you never meet them.
Component events
Section titled “Component events”Components never write to the bus themselves. When something happens to a component, it hands an event to every Signal Emitter on its own entity, and each emitter puts it on its signal. Without a Signal Emitter on the entity, the event goes nowhere and costs nothing.
Every component event has the same shape:
const event = { entityId: 'a1b2c3', eventType: 'UISlider::change', data: { value: 0.4 } };| Field | What it is |
|---|---|
entityId |
The id of the entity that carries the emitter. Pass it to findEntity to reach that entity. |
eventType |
'<Source>::<action>': the component that sent it, and what happened. |
data |
The details; {} when there are none. |
The source is the component’s type without comp-, in PascalCase, with abbreviations such as UI, AI, XR and GLTF in capitals: comp-ui-slider sends UISlider::…, comp-physics-rigid-body sends PhysicsRigidBody::…. The action is lowercase words joined by -: select, collision-enter, position-change.
An on callback on a Signal Emitter’s signal receives the whole event, so you check event.eventType and read event.data.
EventType
Section titled “EventType”EventType names every component event, so you compare against constants instead of typing strings. EventType.<Source>.<Action> holds '<Source>::<action>', with the action in PascalCase: EventType.UISlider.Change is 'UISlider::change', EventType.Transform.PositionChange is 'Transform::position-change'. A misspelt constant is undefined, which is easier to spot than a string that silently never matches.
Common events
Section titled “Common events”A few of the events scripts use most. Each component’s reference page lists the events it sends, and the events reference lists every event with its data.
| Constant | Sent when | data |
|---|---|---|
Event |
The entity is clicked or touched and becomes selected. A click on an already selected entity sends nothing. | { pointer |
Event, Event |
A pointer comes over the entity, or leaves it. Play only. | { pointer |
Event, Event |
A grab begins or ends. | { pointer |
Event |
A UI button is pressed. | {} |
Event |
A UI slider’s value changes. | { value } |
Event |
A UI checkbox is ticked or cleared. | { checked } |
Event |
A UI text field is submitted. | { text } |
Event |
Another collider starts touching this one, once per touching pair. otherEntityId names what touched it, when that is an entity. |
{ other |
Event |
The entity is moved with a setter or a prop edit. | { position } |
Event |
The entity is switched on or off. | { enabled } |
Signal Emitter
Section titled “Signal Emitter”The Signal Emitter (comp-signal-emitter, class SignalEmitterComponent) collects the events of the components on its entity and emits them on the bus under its signal. The editor offers it on every entity that sends events, which is every entity except the scene root.
| Prop | Type | Default | Description |
|---|---|---|---|
signal |
string | '' |
The signal the events are emitted on. Empty: nothing is emitted. |
eventFilter |
string[] | [] |
The eventTypes it lets through, matched exactly, such as ['UIButton::press']. Empty: every event passes. |
- Several per entity. An entity may carry several Signal Emitters, each with its own
signalandeventFilter. Every event reaches all of them, and each lets through what its filter allows. That puts different events of one object on different signals:Selectable::selectonlamp/selectedandSelectable::deselectonlamp/deselected. - Disabled emits nothing. A disabled Signal Emitter forwards no events.
- One signal, many entities. Several entities may emit on the same signal. A listener tells them apart with
event.entityId.
Events that skip the Signal Emitter
Section titled “Events that skip the Signal Emitter”Two kinds of event go straight onto the bus, with the same event shape:
- An Animation Timeline’s signal keys emit
AnimationTimeline::signalon each key’s own signal as playback passes it. See Animation. - A notification shown with a
signaloption emits itsUINotification::open,actionanddismissevents on that signal.
Enable on Signal
Section titled “Enable on Signal”The Enable on Signal component (comp-enable-on-signal, class EnableOnSignalComponent) switches its entity, or some of its components, on or off when a signal arrives: from any entity’s Signal Emitter, its own included, or from a script’s emit. Whatever the signal carries is ignored. It lets you wire interactions without writing code.
| Prop | Type | Default | Description |
|---|---|---|---|
signal |
string | '' |
The signal it listens on. Empty: it listens to nothing. |
action |
'enable' | 'disable' | 'toggle' |
'enable' |
What the signal does. toggle flips each target from its own state. |
targetFilter |
string[] | [] |
The components to switch, by their event source name, such as Outline, UIPanel or PointLight. Empty: the whole entity. |
- It keeps listening while its entity is off. An entity disabled by one Enable on Signal can be switched back on by another, or by the same one toggling. The component itself must be enabled: a disabled Enable on Signal does not listen.
- Toggle flips each named component on its own, or the entity’s own flag, whatever its parents are.
- Play only. Signals are ignored while editing, so the saved state never changes.
- Several per entity, one per signal. Nothing searches the scene or follows parents: every connection is explicit.
Wiring without code
Section titled “Wiring without code”This setup makes a lamp show an outline while it is selected, shows a note next to it at the same time, and lets a UI switch turn its light on and off. No script is involved.
Lamp Selectable Signal Emitter signal: lamp/selected eventFilter: [Selectable::select] Signal Emitter signal: lamp/deselected eventFilter: [Selectable::deselect] Outline (saved disabled) Enable on Signal signal: lamp/selected action: enable targetFilter: [Outline] Enable on Signal signal: lamp/deselected action: disable targetFilter: [Outline]Lamp note (a UI label, saved disabled) Enable on Signal signal: lamp/selected action: enable Enable on Signal signal: lamp/deselected action: disableSwitch Signal Emitter signal: lamp/toggle eventFilter: [UIButton::press]Lamp light Enable on Signal signal: lamp/toggle action: toggleRead it signal by signal: clicking the lamp puts Selectable::select on lamp/selected, which enables the lamp’s Outline and the whole note. Deselecting reverses both. Pressing the switch puts UIButton::press on lamp/toggle, which flips the light. A script can drive the same wiring with emit('lamp/toggle').
Try it
Section titled “Try it”A Selectable and a Grabbable each with a Signal Emitter, and a script that logs their events:
A Selectable that reports clicks and hovers, and a Grabbable you can drag with a mouse, a touch screen or an XR controller. A script listens to both on the event bus.
Hover and click the round shape on the left, then drag the box on the right. Drag to orbit the camera, scroll to zoom.
Examples
Section titled “Examples”1. Talk between two scripts
Section titled “1. Talk between two scripts”One script counts coins; any other script reports a pickup by emitting a signal.
#pragma lifecycle(startup)
let score = 0;
function startup() { on('coin:collected', (data) => { score += data.value; log('Score:', score); if (score >= 10) emit('level:complete', { score: score }); });}#pragma lifecycle(startup, update)
function startup() { log('Press C to collect a coin');}
function update() { if (Input.keyboard.isKeyReleased(Key.C)) emit('coin:collected', { value: 1 });}Two scripts that never reference each other: one emits coin:collected when C is pressed, the other keeps the score and announces level:complete.
Click the scene, then press C and watch the score in the script log.
How it works
emit('coin:collected', { value: 1 })raises the signal with a data object.- Because the signal comes from a script’s
emit, theoncallback receives that data object directly. - The score keeper raises its own signal,
level:complete, for any script that loads the next level. - Neither script holds a reference to the other: they share only the signal name.
2. React to a click
Section titled “2. React to a click”Change an object’s colour when it is clicked. The object carries a Selectable and a Signal Emitter whose signal is box/clicked.
#pragma lifecycle(startup)
function startup() { const box = self.parent; on('box/clicked', (event) => { if (event.eventType !== EventType.Selectable.Select) return; findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again const material = box.getComponent(MaterialComponent); material.setProps({ color: `#${Random.color().getHexString()}` }); log('Clicked', findEntity(event.entityId).name); });}How it works
- The Signal Emitter has no filter, so it forwards every event of the box’s components on
box/clicked: select, deselect, hover, leave. - The callback receives the component event, so it checks
event.eventTypeagainstEventType.Selectable.Selectand ignores the rest. event.entityIdidentifies the entity whose emitter sent it;findEntityturns it back into the entity.event.data.pointerTypesays what clicked: it is absent when a script selected the box.- The Hello cube example uses exactly this wiring.
3. Wire a UI with one listener
Section titled “3. Wire a UI with one listener”A settings panel has a slider and a checkbox, each with a Signal Emitter on settings. One listener handles both.
#pragma lifecycle(startup)
let volume = 1;let music = true;
function startup() { on('settings', (event) => { if (event.eventType === EventType.UISlider.Change) { volume = event.data.value; } else if (event.eventType === EventType.UICheckbox.Change) { music = event.data.checked; } else { return; } emit('settings/changed', { volume: volume, music: music }); });}How it works
- Several entities may emit on the same signal;
eventTypetells their events apart. event.data.valueandevent.data.checkedcarry the new state, as listed in the event table.- The script republishes a simple, script-friendly signal,
settings/changed, that other scripts can listen to without knowing about the UI.
4. Build the outline wiring from a script
Section titled “4. Build the outline wiring from a script”The same lamp wiring as in Wiring without code, created by a script at startup instead of in the editor. This is useful when many objects need the same behaviour.
#pragma lifecycle(startup)
function wire(entity) { const id = entity.entityId; entity.addComponent(new SignalEmitterComponent({ signal: id + '/selected', eventFilter: ['Selectable::select'] })); entity.addComponent(new SignalEmitterComponent({ signal: id + '/deselected', eventFilter: ['Selectable::deselect'] }));
const outline = new OutlineComponent({ color: '#38bdf8' }); entity.addComponent(outline); outline.setEnabled(false);
entity.addComponent(new EnableOnSignalComponent({ signal: id + '/selected', action: 'enable', targetFilter: ['Outline'] })); entity.addComponent(new EnableOnSignalComponent({ signal: id + '/deselected', action: 'disable', targetFilter: ['Outline'] }));}
function startup() { let count = 0; scene.entities.forEach((entity) => { if (!entity.getComponent(SelectableComponent)) return; wire(entity); count += 1; }); log('Wired', count, 'selectable entities');}At startup a script gives every Selectable two filtered Signal Emitters, a disabled Outline and two Enable on Signal components, so selecting an object outlines it with no more code.
Click the shapes: the selected one is outlined. Drag to orbit the camera, scroll to zoom.
How it works
- Each selectable entity gets signals named after its own id, so the wiring of one object never triggers another.
- Two Signal Emitters split select and deselect onto separate signals with
eventFilter. - The Outline starts disabled; the two Enable on Signal components switch only it (
targetFilter: ['Outline']). - After startup the script does nothing more: the components do the work.
5. Drive Enable on Signal from a script
Section titled “5. Drive Enable on Signal from a script”A warning light has an Enable on Signal on alarm/blink with action: 'toggle'. This script raises that signal every half second while an alarm is on.
#pragma lifecycle(startup)
let cancelBlink = null;
function blink() { emit('alarm/blink'); cancelBlink = delay(blink, 500);}
function startup() { on('alarm/start', () => { if (!cancelBlink) blink(); }); on('alarm/stop', () => { if (cancelBlink) cancelBlink(); cancelBlink = null; });}How it works
emit('alarm/blink')reaches the Enable on Signal, which flips the light each time.delayschedules the next blink and returns a function that cancels it.- Any other script, or a UI button’s Signal Emitter on
alarm/start, starts the alarm.
6. A target that counts hits
Section titled “6. A target that counts hits”A target with a collider and a Signal Emitter on target/hits counts what hits it, shows the score on a UI label, and announces it for other scripts.
#pragma lifecycle(startup)
let hits = 0;let label = null;
function show() { if (label) label.setProps({ text: 'Hits: ' + hits });}
function startup() { const scoreboard = findEntity('Score'); label = scoreboard && scoreboard.getComponent(UILabelComponent); show();
on('target/hits', (event) => { if (event.eventType !== EventType.PhysicsCollider.CollisionEnter) return; hits += 1; show(); emit('score/changed', { hits, by: event.data.otherEntityId }); });
on('score/reset', () => { hits = 0; show(); });}How it works
PhysicsCollider::collision-enterarrives once per touching pair, withotherEntityIdnaming what hit the target.- The label is a UI Label entity named
Score;setProps({ text })updates it. emit('score/changed', …)lets any other script react, withon('score/changed', (data) => …).on('score/reset', …)lets a button or another script reset the count.
7. Take turns in execution order
Section titled “7. Take turns in execution order”Two guards both want to react to an alarm. The guard whose Behavior has the lower executionIndex hears it first and takes it, so the other guard leaves it alone.
#pragma slot(ref=guardName, type=String, default="Guard A")#pragma lifecycle(startup)
let busy = false;
function chase(position) { busy = true; log(guardName, 'chasing to', position.x, position.z); Tween.to(self.parent.position, { x: position.x, z: position.z }, { duration: 2 }) .then(() => { busy = false; });}
function startup() { on('alarm', (alarm) => { if (busy || alarm.taken) return; alarm.taken = true; // the guards after this one see it is taken chase(alarm.position); });}An alarm is raised from anywhere with emit('alarm', { position: { x: 4, z: -2 } }).
How it works
- Every guard listens to
alarm, and the guards hear it in execution order: the lowestexecutionIndexfirst. - All listeners receive the same data object, so the first free guard marks it
takenand the guards after it skip it. - A busy guard returns without taking it, so the next guard in the order gets its chance.
- Each guard’s listener is removed by itself when that guard’s script stops.
Common mistakes
Section titled “Common mistakes”Forgetting the Signal Emitter
Section titled “Forgetting the Signal Emitter”A component’s events go nowhere unless its entity has a Signal Emitter: a Selectable on its own sends nothing to scripts. If on never fires, check that the entity carries a Signal Emitter, that it is enabled, and that its signal matches the name you listen to.
Treating a component event as plain data
Section titled “Treating a component event as plain data”on('volume', (value) => { log('Volume', value); // logs the whole event object});on('volume', (event) => { if (event.eventType === EventType.UISlider.Change) log('Volume', event.data.value);});A Signal Emitter’s signal delivers { entityId, eventType, data }. Only a script’s own emit(signal, data) delivers data directly.
Typing event strings
Section titled “Typing event strings”if (event.eventType === 'Selectable::selected') select(); // never true: the action is 'select'if (event.eventType === EventType.Selectable.Select) { findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again select();}Adding listeners every frame
Section titled “Adding listeners every frame”function update() { on('door/open', openDoor); // one more listener every frame}function startup() { on('door/open', openDoor);}Stopping one listener with off
Section titled “Stopping one listener with off”on('door/open', playSound);on('door/open', openDoor);off('door/open'); // stops both listenerson('door/open', playSound);const stopOpening = on('door/open', openDoor);stopOpening(); // stops only openDooroff(signal) stops every listener this script added for that signal. To stop one listener, keep the function on returns and call it.
Using type names in targetFilter
Section titled “Using type names in targetFilter”Enable on Signal’s targetFilter takes event source names, the PascalCase names used in event types: Outline, PointLight, UIPanel. Type strings such as comp-outline match nothing. The same goes for eventFilter, which takes full event types such as Selectable::select.