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.
Before you start
Section titled “Before you start”- New to entities and components? Read Entities and Components in Getting started, and what a world is made of in Basic principles.
- You know what a Behavior script is and how
#pragma lifecycle(startup)runs code once when play starts. See Behavior scripts. - Components explains props,
setPropsand enabling components. - Lifecycle hooks explains
startup,updateanddispose.
What an entity is
Section titled “What an entity is”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.
Getting hold of an entity
Section titled “Getting hold of an 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. |
find |
An entity of the script’s scene, by id, or else by name (the first match). |
event. in an event callback |
The id of the entity that sent a component event; pass it to findEntity. |
spawn(name |
A new copy of an entity, already in the scene. |
new Point and the other entity classes |
A brand-new entity, to add with scene.add. |
Scenes. |
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.
Entity members
Section titled “Entity members”Identity
Section titled “Identity”| 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 find. |
entityType |
Its type, an ent-… string such as 'ent-. |
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 is 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_. Read only. |
Components
Section titled “Components”| Call | What it does |
|---|---|
get or get |
The component of that class or type, or undefined. A base class (Material, Physics) matches any of its kinds. |
get |
Every matching component, in the order added: a new array each call. |
get |
Every component on the entity, in the order added. |
add |
Attach a component you constructed, such as new Outline. Returns the entity. |
remove |
Remove that component. |
remove |
Remove every component of that type. Required components cannot be removed. |
subscribe |
Call listener(kind, component) when a component is 'added', 'removed', 'changed' or 'disposed'. Returns a function that stops listening. |
Transform
Section titled “Transform”| Call | What it does |
|---|---|
set |
Set the local position, in metres. |
set |
Set the local rotation, Euler angles in radians. |
set |
Set the local scale. One number scales evenly. |
set |
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 |
|---|---|
set |
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. |
set |
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. |
Enable and visible
Section titled “Enable and visible”There are two ways to make an entity disappear, and they do very different things.
Enable (set) |
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.
Hierarchy
Section titled “Hierarchy”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.
Choosing
Section titled “Choosing”| If you want … | Use … | Read |
|---|---|---|
| To find an object | find |
Scene and entities |
| To change how an object looks or behaves | entity. |
Components |
| To move an object and keep physics in step | entity. and the other setters |
Transform |
| To turn an object and its children off, and save it off | entity. (the Enable component) |
Enable and visible |
| To hide an object for this session only, without stopping it | entity. |
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 |
In scripts
Section titled “In scripts”These globals are the ones a script uses most with entities and their events:
| Global | What it is |
|---|---|
self | The entity the Behavior is on: self.position, self.getComponent(...). Its own Behavior is self.getComponent(BehaviorComponent). |
scene | The 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. |
findEntity | Find an entity in the current scene by id, a map read fine every frame, or else by name among its entities. |
findObject | Find 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. |
spawn | Copy an entity already in the scene (by name, or the entity itself) and add the copy with options. |
destroy | Same as scene.destroy: remove an entity (or id) and its subtree, disposing them and stopping their scripts. |
isEntity | Whether an object is an Entity, and so has components. |
emit | Raise a signal, with optional data, for every script and the app. |
on | Call callback(data) right away each time signal is emitted; returns a function that stops it. Released with the script. |
once | Call callback(data) the next time signal is emitted, then stop; returns a function that stops it sooner. Released with the script. |
off | Stop every listener this script added with on or once for signal; other scripts keep theirs. |
EventType | Every 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.
Examples
Section titled “Examples”1. Describe the entity a script is on
Section titled “1. Describe the entity a script is on”The simplest script reads the members of its own entity and its parent.
#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:
selfis the Behavior entity that holds the script.entityTypeandentityIdare entity members;nameandparentcome fromObject3D.isEntitychecks that the parent is an entity, and not a plain object.
2. Count the entities of each type
Section titled “2. Count the entities of each type”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.
#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:
sceneis the scene the script’s entity is in.scene.entitiesholds 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.
3. Change a component
Section titled “3. Change a component”This script finds a lamp by name and makes its light brighter and warmer.
#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);}A script finds the entity named Lamp and makes its Point Light brighter and warmer with setProps.
Open the script log to read the new intensity. Drag to orbit the camera, scroll to zoom.
How it works:
findEntity('Lamp')finds an entity by name, or returnsundefined. 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.setPropschanges only the props you pass;propsreads the current values.
4. Place and aim an object
Section titled “4. Place and aim an object”This script places a spotlight rig above the origin and turns it to face a target, with one chained call.
#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:
getWorldPositionfillsatwith the statue’s position in the world.setLookAttakes a world point, so the rig faces the statue whatever its parents are.- The setters return the entity, so
setPosition(…).setLookAt(…)chains.
5. A beacon that blinks, and a gate that switches off
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.
#pragma lifecycle(startup, update)
const BLINK = 0.5; // seconds per statelet 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.visibletoggles 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 theirdisablehooks run.- Another script, or a Signal Emitter, raises
gate/openwithemit('gate/open'). - The lookups happen once, in
startup;updateonly uses the stored entities.
6. Highlight what the player selects
Section titled “6. Highlight what the player selects”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.
#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); });}One script serves every crate: it adds an Outline component to the crate that is selected and removes it when the crate is deselected.
Click a crate, then another. Drag to orbit the camera, scroll to zoom.
How it works:
- One script serves every crate:
event.entityIdsays which one sent the event, andfindEntity(id)is instant. highlightchecks 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.
#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.valueanimates 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
oncallback isasync, so it canawaitthe tween before logging.
8. Watch an entity’s components
Section titled “8. Watch an entity’s components”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.
#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:
subscribeComponentChangescalls the listener with the kind of change and the component concerned.- It returns a function that stops the listener;
disposecalls 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.
#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
rotationandpositiondirectly: the coin is decorative and its sensor only needs to be roughly in place. - A sensor collider sends
PhysicsCollider::intersection-enterwhen something enters it. - The
entityIdcheck 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.
Common mistakes
Section titled “Common mistakes”Passing degrees to a rotation
Section titled “Passing degrees to a rotation”Every rotation is in radians. setRotation(0, 90, 0) turns the entity about 14 full turns plus a bit.
door.setRotation(0, 90, 0);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.
crate.position.y = 5;crate.setPosition(crate.position.x, 5, crate.position.z);Hiding an entity and expecting it to stop
Section titled “Hiding an entity and expecting it to stop”visible = false only stops drawing. Scripts, physics, animation and sounds carry on.
// The enemy is invisible, but its script still chases the player.enemy.visible = false;// Disabled: its scripts pause and it stops colliding.enemy.setEnabled(false);Forgetting to stop a component listener
Section titled “Forgetting to stop a component listener”subscribeComponentChanges keeps calling its listener until you stop it. Keep the function it returns and call it in dispose, as in Example 8.