Skip to content

Working with entities

Updated

Most scripts do the same few things with entities: get hold of one, reach one of its components, change a prop, move it, switch it on or off. This page is the practical guide to those tasks. It lists every entity member a script uses, explains when to choose one over another, and builds up to complete scripts you can adapt.

An entity is a scene object (an Object3D) with three additions: a unique id, a type, and a collection of components. Because it is an Object3D, an entity has everything a scene object has: position, rotation, scale, quaternion, parent, children, name, and methods such as add, getWorldPosition or lookAt. Because it has components, it can also draw, light, collide, play sound and run scripts.

An entity’s id is what a scene uses to refer to it. Ids are fixed: renaming an entity in the editor changes its name, never its entityId. Several entities may share a name, but never an id, so an id is the reliable way to refer to one particular entity. Component events report the id of the entity they come from (event.entityId), and findEntity(id) turns it back into the entity.

From Gives you
self The entity the script is on.
self.parent The entity the script’s entity sits under: the usual way for a script to drive “its” object.
findEntity(idOrName) An entity of the script’s scene, by id, or else by name (the first match).
event.entityId in an event callback The id of the entity that sent a component event; pass it to findEntity.
spawn(nameOrEntity, options?) A new copy of an entity, already in the scene.
new PointLightEntity() and the other entity classes A brand-new entity, to add with scene.add.
Scenes.find(nameOrId).findEntity(id) An entity of another loaded scene. See Scene switching.

By id, findEntity is instant, even every frame. By name, it looks through the scene’s entities: do it once, in startup, and keep the result in a variable. Scene and entities covers these globals in detail.

Member What it is
entityId The entity’s id: unique in its scene, and kept when the scene is saved. Read only.
eid Short for entityId.
name Its display name, as shown in the editor and used by findEntity(name).
entityType Its type, an ent-… string such as 'ent-primitive-mesh'.
components Its components, in a Map keyed by type. Use getComponent rather than reading it directly.
parent, children Its place in the scene tree, as for any scene object.
isEntity Always true. The isEntity(object) global tests any object for it.
dontUnload Whether the entity is marked to survive a scene switch, by a Don’t Unload component or a script’s #pragma dont_unload(). Read only.
Call What it does
getComponent(Class) or getComponent('comp-…') The component of that class or type, or undefined. A base class (MaterialComponent, PhysicsColliderComponent) matches any of its kinds.
getComponents(Class) Every matching component, in the order added: a new array each call.
getAllComponents() Every component on the entity, in the order added.
addComponent(component) Attach a component you constructed, such as new OutlineComponent(). Returns the entity.
removeComponent(component) Remove that component.
removeComponent('comp-…') Remove every component of that type. Required components cannot be removed.
subscribeComponentChanges(listener) Call listener(kind, component) when a component is 'added', 'removed', 'changed' or 'disposed'. Returns a function that stops listening.
Call What it does
setPosition(x, y, z) Set the local position, in metres.
setRotation(x, y, z) Set the local rotation, Euler angles in radians.
setScale(x, y?, z?) Set the local scale. One number scales evenly.
setLookAt(x, y, z) Turn the entity to face a point in world space.

The setters move the entity’s physics body and colliders with it, and send the Transform events. Each returns the entity, so they chain. Transform axis locks never stop them: locks guard only the editor’s gizmo.

You can also write the transform members directly: position, rotation, scale, quaternion. A direct write is the quickest way to animate a purely visual object every frame, but it sends no events and does not move colliders. See Common components.

Member What it does
setEnabled(on) Switch the entity and its subtree on or off. Off: not drawn, no ticking, no physics, no side effects, scripts paused. Saved. Returns the entity.
isEnabled() Whether it is effectively on: its own flag and every ancestor’s.
visible Read: whether it is drawn by its own flags: not hidden, and enabled. Write: hide or show it for this session only, without stopping anything. Never saved.
isShown() Whether it is enabled and neither it nor any ancestor is hidden.
setLayer(layer) Put the entity on a user layer, 0 to 20. Returns the entity.
setLocked(on) Lock or unlock it against selection and transforming in the editor. Returns the entity.

There are two ways to make an entity disappear, and they do very different things.

Enable (setEnabled(false)) visible = false
Drawn No No
Scripts Paused: no update, disable runs Keep running
Physics, animation, timelines Stopped Keep running
Audio and video Stopped Audio keeps playing, muted, and is heard again when shown
Pointers Pass through Pass through, for it and its subtree
Saved with the scene Yes No: every entity loads shown
Affects children Yes, the whole subtree Yes, the whole subtree

Use Enable to turn something off: a door that is gone, a level section not yet reached, a menu that is closed. Use visible to hide something briefly while it keeps working: a blinking marker, a reticle shown only when it points at something, an object hidden by a level-of-detail switch.

Entities are scene objects, so the scene tree works as you would expect: parent, children, add(child), getWorldPosition(target), traverse(callback) and so on. children is the list of objects directly under an entity; it can also hold plain objects, such as the meshes a model is made of, so filter it with isEntity to keep only entities, the objects that have components. Use destroy(entity) to remove an entity for good: it disposes it and its subtree and stops their scripts.

If you want … Use … Read
To find an object findEntity(nameOrId) Scene and entities
To change how an object looks or behaves entity.getComponent(Class).setProps({ … }) Components
To move an object and keep physics in step entity.setPosition(x, y, z) and the other setters Transform
To turn an object and its children off, and save it off entity.setEnabled(false) (the Enable component) Enable and visible
To hide an object for this session only, without stopping it entity.visible = false Enable and visible
To react to clicks, collisions and other component events A Signal Emitter plus on(signal, callback) Events and signals
To switch things on and off without code Enable on Signal Events and signals
To make a group of objects unclickable or switch them off together Layers Layers

These globals are the ones a script uses most with entities and their events:

GlobalWhat it is
selfThe entity the Behavior is on: self.position, self.getComponent(...). Its own Behavior is self.getComponent(BehaviorComponent).
sceneThe current scene fragment; live, so it always reflects the loaded scene. To delete an entity use scene.destroy(entity): it stops its scripts and frees its memory. scene.remove(entity) (and scene.clear()) stop the scripts but keep the memory, for an entity you will add back later.
findEntityFind an entity in the current scene by id, a map read fine every frame, or else by name among its entities.
findObjectFind any object in the current scene by name, a bone or a mesh inside a model too. Walks the scene: look up once and keep it.
spawnCopy an entity already in the scene (by name, or the entity itself) and add the copy with options.
destroySame as scene.destroy: remove an entity (or id) and its subtree, disposing them and stopping their scripts.
isEntityWhether an object is an Entity, and so has components.
emitRaise a signal, with optional data, for every script and the app.
onCall callback(data) right away each time signal is emitted; returns a function that stops it. Released with the script.
onceCall callback(data) the next time signal is emitted, then stop; returns a function that stops it sooner. Released with the script.
offStop every listener this script added with on or once for signal; other scripts keep theirs.
EventTypeEvery event type a script can hear, by who sends it: compare them rather than typing the strings.

Every component class (such as PointLightComponent) and every entity class (such as PointLightEntity) is a global too. See the globals reference.

The simplest script reads the members of its own entity and its parent.

WhoAmI.jx
#pragma lifecycle(startup)
function startup() {
const me = self;
log('I am', me.name, 'of type', me.entityType, 'with id', me.entityId);
const target = me.parent;
if (isEntity(target)) {
log('My parent is', target.name, '(' + target.entityType + ')');
} else {
log('I sit at the top of the scene');
}
}

How it works:

  • self is the Behavior entity that holds the script.
  • entityType and entityId are entity members; name and parent come from Object3D.
  • isEntity checks that the parent is an entity, and not a plain object.

scene.entities is a Map of every entity in the scene, by id. This script counts them by type, which is handy to check a scene’s contents.

SceneCensus.jx
#pragma lifecycle(startup)
function startup() {
const counts = new Map();
scene.entities.forEach((entity) => {
counts.set(entity.entityType, (counts.get(entity.entityType) || 0) + 1);
});
log('This scene has', scene.entities.size, 'entities');
counts.forEach((count, type) => log(' ', type, count));
}

How it works:

  • scene is the scene the script’s entity is in.
  • scene.entities holds entities only, never plain objects such as the meshes inside a loaded model.
  • The script runs once, in startup, because walking every entity every frame would be wasteful.

This script finds a lamp by name and makes its light brighter and warmer.

WarmLamp.jx
#pragma lifecycle(startup)
function startup() {
const lamp = findEntity('Lamp');
if (!lamp) {
log('No entity named Lamp in this scene');
return;
}
const light = lamp.getComponent(PointLightComponent);
light.setProps({ intensity: 3, color: '#ffd8a8' });
log('Lamp intensity is now', light.props.intensity);
}

How it works:

  • findEntity('Lamp') finds an entity by name, or returns undefined. The guard keeps the script from failing when the lamp is missing.
  • getComponent(PointLightComponent) returns the lamp’s Point Light component. Component classes are globals.
  • setProps changes only the props you pass; props reads the current values.

This script places a spotlight rig above the origin and turns it to face a target, with one chained call.

AimRig.jx
#pragma lifecycle(startup)
function startup() {
const rig = findEntity('Spot Rig');
const target = findEntity('Statue');
if (!rig || !target) {
log('Spot Rig or Statue is missing');
return;
}
const at = new THREE.Vector3();
target.getWorldPosition(at);
rig.setPosition(0, 4, 3).setLookAt(at.x, at.y, at.z);
log(rig.name, 'aims at', target.name);
}

How it works:

  • getWorldPosition fills at with the statue’s position in the world.
  • setLookAt takes a world point, so the rig faces the statue whatever its parents are.
  • The setters return the entity, so setPosition(…).setLookAt(…) chains.
Section titled “5. A beacon that blinks, and a gate that switches off”

This script shows the difference between hiding and disabling. The beacon blinks with visible while it keeps running; the gate is disabled when a signal arrives, which also stops everything under it.

BeaconAndGate.jx
#pragma lifecycle(startup, update)
const BLINK = 0.5; // seconds per state
let beacon = null;
let gate = null;
let clock = 0;
function openGate() {
if (!gate || !gate.isEnabled()) return;
gate.setEnabled(false);
log('Gate switched off. Still shown?', gate.isShown());
}
function startup() {
beacon = findEntity('Beacon');
gate = findEntity('Gate');
on('gate/open', openGate);
}
function update(dt) {
if (!beacon) return;
clock += dt;
if (clock >= BLINK) {
clock = 0;
beacon.visible = !beacon.visible;
}
}

How it works:

  • beacon.visible toggles drawing only; anything on the beacon keeps running, and nothing is saved.
  • gate.setEnabled(false) switches the gate and its subtree off: scripts under it pause and their disable hooks run.
  • Another script, or a Signal Emitter, raises gate/open with emit('gate/open').
  • The lookups happen once, in startup; update only uses the stored entities.

Every crate has a Selectable and a Signal Emitter on crate/selection. This script adds an Outline to the crate that is selected, and removes it when it is deselected.

SelectionHighlight.jx
#pragma lifecycle(startup)
function highlight(entity, selected) {
const outline = entity.getComponent(OutlineComponent);
if (selected && !outline) entity.addComponent(new OutlineComponent({ color: '#facc15', thickness: 5 }));
if (!selected && outline) entity.removeComponent(outline);
}
function startup() {
on('crate/selection', (event) => {
const crate = findEntity(event.entityId);
if (!crate) return;
if (event.eventType === EventType.Selectable.Select) highlight(crate, true);
if (event.eventType === EventType.Selectable.Deselect) highlight(crate, false);
});
}

How it works:

  • One script serves every crate: event.entityId says which one sent the event, and findEntity(id) is instant.
  • highlight checks for an existing Outline first, so a second select never adds a second one.
  • removeComponent(outline) removes exactly that component.

7. Open a door smoothly, keeping physics in step

Section titled “7. Open a door smoothly, keeping physics in step”

A tween can write a rotation directly, but then the door’s collider would not turn. This script tweens a plain number and applies it with setRotation, so the collider follows.

Door.jx
#pragma lifecycle(startup)
let door = null;
let open = false;
function swing(from, to) {
return Tween.value(from, to, (angle) => door.setRotation(0, angle, 0), {
duration: 0.8,
ease: Ease.InOutCubic,
});
}
function startup() {
door = findEntity('Door');
if (!door) return;
on('door/toggle', async () => {
const from = door.rotation.y;
const to = open ? 0 : DEG_TO_RAD(90);
open = !open;
await swing(from, to);
log('Door', open ? 'open' : 'closed');
});
}

How it works:

  • Tween.value animates a number and hands each value to the callback.
  • door.setRotation(0, angle, 0) moves the door and its collider, and sends Transform events.
  • DEG_TO_RAD(90) converts degrees to radians; rotations are always in radians.
  • The on callback is async, so it can await the tween before logging.

This script logs every component change on a target, such as a material being edited by another script or an Outline being added, and stops listening when it stops.

ComponentWatch.jx
#pragma lifecycle(startup, dispose)
let stop = null;
function startup() {
const target = findEntity('Crate');
if (!target) return;
stop = target.subscribeComponentChanges((kind, component) => {
log(target.name, kind, component ? component.type : '');
});
}
function dispose() {
if (stop) stop();
}

How it works:

  • subscribeComponentChanges calls the listener with the kind of change and the component concerned.
  • It returns a function that stops the listener; dispose calls it when the script stops.
  • Combine it with Example 6 to watch Outlines come and go.

9. A pickup that spins, collects and disappears

Section titled “9. A pickup that spins, collects and disappears”

A complete pickup: it spins and bobs while it waits, and when the player touches it, it shrinks, reports the coin and is destroyed. The pickup has a collider set as a sensor (see Physics) and a Signal Emitter on pickup/touch; the Behavior entity sits under it.

Pickup.jx
#pragma lifecycle(startup, update)
let coin = null;
let baseY = 0;
let taken = false;
async function collect() {
taken = true;
await Tween.to(coin.scale, { x: 0, y: 0, z: 0 }, { duration: 0.3, ease: Ease.InBack });
emit('coin', 1);
destroy(coin);
}
function startup() {
coin = self.parent;
baseY = coin.position.y;
on('pickup/touch', (event) => {
if (taken) return;
if (event.eventType !== EventType.PhysicsCollider.IntersectionEnter) return;
if (event.entityId !== coin.entityId) return;
collect();
});
}
function update(dt, time) {
if (taken) return;
coin.rotation.y += dt * 2;
coin.position.y = baseY + Math.sin(time * 3) * 0.1;
}

How it works:

  • The spin and bob write rotation and position directly: the coin is decorative and its sensor only needs to be roughly in place.
  • A sensor collider sends PhysicsCollider::intersection-enter when something enters it.
  • The entityId check ignores events from other pickups that share the signal.
  • destroy(coin) removes the coin and its subtree, including this Behavior entity, whose script then stops.

Every rotation is in radians. setRotation(0, 90, 0) turns the entity about 14 full turns plus a bit.

Wrong
door.setRotation(0, 90, 0);
Right
door.setRotation(0, DEG_TO_RAD(90), 0);

Moving a physics object with a direct write

Section titled “Moving a physics object with a direct write”

A body moved through position leaves its collider behind. Use the setters for anything with a collider.

Wrong
crate.position.y = 5;
Right
crate.setPosition(crate.position.x, 5, crate.position.z);

visible = false only stops drawing. Scripts, physics, animation and sounds carry on.

Wrong
// The enemy is invisible, but its script still chases the player.
enemy.visible = false;
Right
// Disabled: its scripts pause and it stops colliding.
enemy.setEnabled(false);

subscribeComponentChanges keeps calling its listener until you stop it. Keep the function it returns and call it in dispose, as in Example 8.