Skip to content

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.

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 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(object) Add an entity or a plain object at the top of the scene.
scene.findEntity(id) An entity by id only.
scene.entities 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.destroy(entity or id) Remove an entity and its subtree, stop their scripts and free their memory. Same as the destroy global.
scene.remove(object), 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.

Global What it does
findEntity(idOrName) 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.
findObject(name) Any object of scene by name, including a bone or a mesh inside a loaded model; the first match, or undefined.
isEntity(object) 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.

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

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.AudioListener, 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 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.get(name, fallback?) 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);

Find a door once, then swing it open when the player presses O and shut when they press C.

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

How it works

  • findEntity('Door') runs once in startup, because a lookup by name walks the scene.
  • The script checks for undefined and logs a clear message when the door is missing.
  • setRotation turns the door and keeps its collider in step, so the player can walk through when it is open.
  • open remembers the door’s state, so O only opens a closed door and C only closes an open one.

Copy a disabled Enemy template five times in a row, and remove each copy after thirty seconds.

WaveSpawner.jx
#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 Enemy entity is saved disabled in the scene, so the template itself never plays; enabled: true switches each copy on.
  • spawn returns the new entity, and any Behavior inside it starts on its own.
  • delay schedules destroy for 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').

Create a point light above the parent object and add a glowing sphere next to it with THREE.

LampBuilder.jx
#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.add puts it at the top of the scene; setPosition places it.
  • getComponent(PointLightComponent).setProps(...) changes its light.
  • A plain THREE.Mesh can sit under an entity with lamp.add. It is not an entity, so it has no components.

This script creates two entities from their classes, configures them, and adds them to the scene.

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

How it works:

  • new PointLightEntity() makes an entity with a Point Light component already attached; getComponent reaches it.
  • new PrimitiveMeshEntity() starts with a Geometry and a material. MaterialComponent finds 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.
Wrong
function update(dt) {
findEntity('Fan').rotation.y += dt; // walks the scene's entities every frame
}
Right
let fan = null;
function startup() {
fan = findEntity('Fan');
}
function update(dt) {
if (fan) fan.rotation.y += dt;
}
Wrong
scene.remove(enemy); // its memory stays until it is added back
Right
destroy(enemy); // disposes it and everything under it

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

Wrong
const lamp = new PointLightEntity();
lamp.setPosition(0, 3, 0);
Right
const lamp = new PointLightEntity();
lamp.setPosition(0, 3, 0);
scene.add(lamp);

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.

Wrong
// Every crate is called "Crate": this always finds the same one.
on('crate/clicked', () => findEntity('Crate').setEnabled(false));
Right
on('crate/clicked', (event) => findEntity(event.entityId)?.setEnabled(false));

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.