Skip to content

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.

  • Scripts usually start listening in their startup hook, declared with #pragma lifecycle(...). See Lifecycle hooks.
  • Components can be enabled and disabled. See Components.

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.

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.

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.

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

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
EventType.Selectable.Select The entity is clicked or touched and becomes selected. A click on an already selected entity sends nothing. { pointerType? }
EventType.Selectable.Hover, EventType.Selectable.Leave A pointer comes over the entity, or leaves it. Play only. { pointerType }
EventType.Grabbable.Start, EventType.Grabbable.End A grab begins or ends. { pointerType }
EventType.UIButton.Press A UI button is pressed. {}
EventType.UISlider.Change A UI slider’s value changes. { value }
EventType.UICheckbox.Change A UI checkbox is ticked or cleared. { checked }
EventType.UIInput.Submit A UI text field is submitted. { text }
EventType.PhysicsCollider.CollisionEnter Another collider starts touching this one, once per touching pair. otherEntityId names what touched it, when that is an entity. { otherEntityId?, contact? }
EventType.Transform.PositionChange The entity is moved with a setter or a prop edit. { position }
EventType.Enable.Change The entity is switched on or off. { enabled }

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 signal and eventFilter. 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::select on lamp/selected and Selectable::deselect on lamp/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.

Two kinds of event go straight onto the bus, with the same event shape:

  • An Animation Timeline’s signal keys emit AnimationTimeline::signal on each key’s own signal as playback passes it. See Animation.
  • A notification shown with a signal option emits its UINotification::open, action and dismiss events on that 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.

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: disable
Switch Signal Emitter signal: lamp/toggle eventFilter: [UIButton::press]
Lamp light Enable on Signal signal: lamp/toggle action: toggle

Read 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').

A Selectable and a Grabbable each with a Signal Emitter, and a script that logs their events:

One script counts coins; any other script reports a pickup by emitting a signal.

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

How it works

  • emit('coin:collected', { value: 1 }) raises the signal with a data object.
  • Because the signal comes from a script’s emit, the on callback 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.

Change an object’s colour when it is clicked. The object carries a Selectable and a Signal Emitter whose signal is box/clicked.

ClickColour.jx
#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.eventType against EventType.Selectable.Select and ignores the rest.
  • event.entityId identifies the entity whose emitter sent it; findEntity turns it back into the entity.
  • event.data.pointerType says what clicked: it is absent when a script selected the box.
  • The Hello cube example uses exactly this wiring.

A settings panel has a slider and a checkbox, each with a Signal Emitter on settings. One listener handles both.

Settings.jx
#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; eventType tells their events apart.
  • event.data.value and event.data.checked carry 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.

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.

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

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.

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.

AlarmBlink.jx
#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.
  • delay schedules 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.

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.

HitCounter.jx
#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-enter arrives once per touching pair, with otherEntityId naming 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, with on('score/changed', (data) => …).
  • on('score/reset', …) lets a button or another script reset the count.

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.

Guard.jx
#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 lowest executionIndex first.
  • All listeners receive the same data object, so the first free guard marks it taken and 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.

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.

Wrong
on('volume', (value) => {
log('Volume', value); // logs the whole event object
});
Right
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.

Wrong
if (event.eventType === 'Selectable::selected') select(); // never true: the action is 'select'
Right
if (event.eventType === EventType.Selectable.Select) {
findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again
select();
}
Wrong
function update() {
on('door/open', openDoor); // one more listener every frame
}
Right
function startup() {
on('door/open', openDoor);
}
Wrong
on('door/open', playSound);
on('door/open', openDoor);
off('door/open'); // stops both listeners
Right
on('door/open', playSound);
const stopOpening = on('door/open', openDoor);
stopOpening(); // stops only openDoor

off(signal) stops every listener this script added for that signal. To stop one listener, keep the function on returns and call it.

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.