Scene and entities
Updated
A Behavior script almost always works on objects: the entity it is attached to, the object above it, a door somewhere else in the level, a copy of an enemy it spawns. This page covers the globals that reach those objects. self is the script’s own entity; scene is the scene that entity is in; findEntity, findObject, spawn and destroy find, copy and remove entities; camera and audioListener reach the view; and Environment reads the project’s variables.
Before you start
Section titled “Before you start”- An entity is an object in a scene, and its components give it everything it does. See Working with entities and Components.
- Hooks such as
startupandupdateare declared with#pragma lifecycle(...). See Lifecycle hooks.
self is the entity the script’s Behavior is on, and self.getComponent(BehaviorComponent) is that Behavior. In the editor you usually add a script as a Behavior entity and place it under the object it drives, so self.parent is that object.
self.setEnabled(false)pauses the Behavior entity and everything under it.self.getComponent(BehaviorComponent).setEnabled(false)pauses only this script, when the Behavior sits on an entity that does other things too.
What you can do with an entity once you have it, self included (its components and props, the transform setters, enabling and hiding), is covered in Working with entities.
scene: the current scene
Section titled “scene: the current scene”scene is the scene the Behavior’s entity is in: a THREE.Scene that holds entities and plain objects. It is live: when a Don’t Unload entity is carried to a new scene, scene refers to the new one from then on.
| Member | What it does |
|---|---|
scene.name |
The scene’s name. |
scene. |
Add an entity or a plain object at the top of the scene. |
scene. |
An entity by id only. |
scene. |
A Map of every entity in the scene, by id. |
scene.rootId |
The id of the scene’s root entity, which carries scene-wide components such as sky, fog and environment. |
scene. |
Remove an entity and its subtree, stop their scripts and free their memory. Same as the destroy global. |
scene., scene.clear() |
Take objects out but keep their memory, for an entity you add back later. Their scripts stop. |
To reach another loaded scene, use Scenes.find(nameOrId), which returns the same kind of object. See Scene switching.
Finding entities and objects
Section titled “Finding entities and objects”| Global | What it does |
|---|---|
find |
An entity of scene by its id, else by name; the first match when several share a name. Only ever returns an entity, or undefined. |
find |
Any object of scene by name, including a bone or a mesh inside a loaded model; the first match, or undefined. |
is |
Whether object is an entity, and so has components. |
Cost. By id, findEntity is a map read: instant at any scene size, fine every frame. By name, it looks through the scene’s entities, and findObject walks the whole scene. Look things up by name once, in startup, and keep the result.
Spawning and destroying
Section titled “Spawning and destroying”spawn(source, options?) copies an entity already in scene, found by name or passed directly, gives the copy fresh ids, and adds it. The copy keeps every component and child of the original. Behaviors inside the copy start like any other. It throws when no entity has that name. A common pattern is a template: an entity saved disabled, out of play, that scripts copy with enabled: true. This is the usual way to make many of something: author one template, keep it disabled, and spawn copies.
| Option | Type | What it sets |
|---|---|---|
parent |
entity | Where the copy goes; the scene’s root by default. |
position |
{ x, y, z } |
Local position. A THREE.Vector3 works too. |
rotation |
{ x, y, z } |
Local rotation, Euler angles in radians. |
scale |
number or { x, y, z } |
Local scale; a number scales evenly. |
visible |
boolean | Whether it is shown, for this session. |
enabled |
boolean | Whether it is on. Pass true when you copy a disabled template. |
destroy(target) removes an entity, or the entity with that id, with its subtree. Every entity in it is disposed: their scripts stop (dispose runs) and their resources are freed. A plain object has nothing to dispose: take it out with scene.remove.
To build a brand new entity instead of copying one, construct its class and add it: scene.add(new PointLightEntity()). Every entity class is a global, named after its type: PrimitiveMeshEntity, PointLightEntity, GroupEntity, UILabelEntity and so on. A new entity starts with its type’s default components. Add it to the scene with scene.add(entity), or under another entity with parent.add(entity).
Camera and listener
Section titled “Camera and listener”| Global | What it is |
|---|---|
camera |
The camera the player sees through: the one the camera director cut to, or the main camera. Live, so a camera switch reaches every script at once. undefined until rendering starts. |
audioListener |
The shared THREE., parented to the camera. Live, undefined until rendering starts. |
Read them when you need them instead of keeping a copy from startup, which can run before rendering starts. To choose which camera renders, for a cutscene, a security-camera view or a map view, use the CameraDirector global: see Camera director.
Environment
Section titled “Environment”Environment reads the project’s variables: values set per project, such as an API address or a feature switch, so the same script works in several setups. It is read-only and has one method.
| Call | What it returns |
|---|---|
Environment. |
The variable’s value, or fallback when it is not set. |
const apiUrl = Environment.get('API_URL', 'http://localhost:8080');const verbose = Environment.get('VERBOSE_LOGS', false);Examples
Section titled “Examples”1. Open a door by name
Section titled “1. Open a door by name”Find a door once, then swing it open when the player presses O and shut when they press C.
#pragma lifecycle(startup, update)
let door = null;let open = false;
function startup() { door = findEntity('Door'); if (!door) log('No entity named Door in', scene.name);}
function update() { if (!door) return; if (!open && Input.keyboard.isKeyReleased(Key.O)) { open = true; door.setRotation(0, DEG_TO_RAD(90), 0); log(door.name, 'opened'); } if (open && Input.keyboard.isKeyReleased(Key.C)) { open = false; door.setRotation(0, 0, 0); log(door.name, 'closed'); }}A script finds the entity named Door once, then swings it open with setRotation when O is pressed and shut when C is pressed.
Click the scene, then press O to open the door and C to close it. Drag to orbit the camera, scroll to zoom.
How it works
findEntity('Door')runs once instartup, because a lookup by name walks the scene.- The script checks for
undefinedand logs a clear message when the door is missing. setRotationturns the door and keeps its collider in step, so the player can walk through when it is open.openremembers the door’s state, so O only opens a closed door and C only closes an open one.
2. Spawn a wave from a template
Section titled “2. Spawn a wave from a template”Copy a disabled Enemy template five times in a row, and remove each copy after thirty seconds.
#pragma slot(ref=count, type=Integer, min=1, max=20, default=5)#pragma lifecycle(startup)
function spawnWave() { for (let i = 0; i < count; i++) { const enemy = spawn('Enemy', { position: { x: i * 2 - count, y: 0, z: -10 }, rotation: { x: 0, y: Math.PI, z: 0 }, enabled: true, }); delay(() => destroy(enemy), 30000); } log('Spawned', count, 'enemies');}
function startup() { on('enemy/wave', spawnWave);}How it works
- The
Enemyentity is saved disabled in the scene, so the template itself never plays;enabled: trueswitches each copy on. spawnreturns the new entity, and any Behavior inside it starts on its own.delayschedulesdestroyfor each copy; when this script stops first, the pending calls are cancelled.- Another script, or a button wired through a Signal Emitter, starts a wave with
emit('enemy/wave').
3. Build an entity from scratch
Section titled “3. Build an entity from scratch”Create a point light above the parent object and add a glowing sphere next to it with THREE.
#pragma lifecycle(startup)
function startup() { const target = self.parent;
const lamp = new PointLightEntity(); lamp.name = 'Generated lamp'; scene.add(lamp); lamp.setPosition(target.position.x, target.position.y + 2, target.position.z); lamp.getComponent(PointLightComponent).setProps({ color: '#ffd8a8', intensity: 3 });
const bulb = new THREE.Mesh( new THREE.SphereGeometry(0.1), new THREE.MeshBasicMaterial({ color: '#ffd8a8' }), ); lamp.add(bulb);}How it works
- Every entity class is a global, so
new PointLightEntity()builds a light entity with its required components. scene.addputs it at the top of the scene;setPositionplaces it.getComponent(PointLightComponent).setProps(...)changes its light.- A plain
THREE.Meshcan sit under an entity withlamp.add. It is not an entity, so it has no components.
4. Build a lamp and a marker from code
Section titled “4. Build a lamp and a marker from code”This script creates two entities from their classes, configures them, and adds them to the scene.
#pragma lifecycle(startup)
function startup() { const lamp = new PointLightEntity(); lamp.name = 'Script Lamp'; lamp.getComponent(PointLightComponent).setProps({ color: '#ffd8a8', intensity: 4 }); lamp.setPosition(0, 2.5, 0); scene.add(lamp);
// A small sphere marks where the lamp is. const marker = new PrimitiveMeshEntity(); marker.getComponent(GeometryComponent).setProps({ shape: 'sphere' }); marker.getComponent(MaterialComponent).setProps({ color: '#facc15' }); marker.setScale(0.2); lamp.add(marker);
log('Built', lamp.name, 'with id', lamp.entityId);}A script builds a PointLightEntity and a PrimitiveMeshEntity from their classes, configures their components and adds them to the scene.
Look for the yellow marker above the table. Drag to orbit the camera, scroll to zoom.
How it works:
new PointLightEntity()makes an entity with a Point Light component already attached;getComponentreaches it.new PrimitiveMeshEntity()starts with a Geometry and a material.MaterialComponentfinds the material whatever its kind.setScale(0.2)with one number scales evenly.lamp.add(marker)makes the marker a child, so it follows the lamp.
Common mistakes
Section titled “Common mistakes”Looking up by name every frame
Section titled “Looking up by name every frame”function update(dt) { findEntity('Fan').rotation.y += dt; // walks the scene's entities every frame}let fan = null;
function startup() { fan = findEntity('Fan');}
function update(dt) { if (fan) fan.rotation.y += dt;}Using remove to delete an entity
Section titled “Using remove to delete an entity”scene.remove(enemy); // its memory stays until it is added backdestroy(enemy); // disposes it and everything under itConstructing an entity and never adding it
Section titled “Constructing an entity and never adding it”A new entity is not part of any scene until you add it. It is not drawn and its components do not run.
const lamp = new PointLightEntity();lamp.setPosition(0, 3, 0);const lamp = new PointLightEntity();lamp.setPosition(0, 3, 0);scene.add(lamp);Relying on a name that is not unique
Section titled “Relying on a name that is not unique”findEntity(name) returns the first match when several entities share a name. When you need one particular entity, keep its id (for example from event.entityId) and look it up by id.
// Every crate is called "Crate": this always finds the same one.on('crate/clicked', () => findEntity('Crate').setEnabled(false));on('crate/clicked', (event) => findEntity(event.entityId)?.setEnabled(false));Spawning from an enabled template
Section titled “Spawning from an enabled template”If the template is enabled in the scene, it plays too: an extra enemy stands at the template’s place. Save the template disabled and pass enabled: true to spawn.