ScriptBehaviourSystem
Loads user-authored Behaviour scripts via dynamic import(), instantiates their classes, and drives the full Behaviour lifecycle (init, onUpdate, onDestroy) each frame.
Overview
ScriptBehaviourSystem runs every frame and is responsible for:
- Discovering entities with a
ScriptComponentand iterating theirentriesarray. - Dynamically importing each script's compiled URL the first time it is seen (or when the URL changes).
- Resolving the exported
Behavioursubclass by name (or falling back to the default export). - Instantiating the class and calling
init()once. - Calling
onUpdate(deltaTime)on every active script instance each frame, oronPausedUpdate()while the world is paused. - Detecting stale instances (removed entries, changed URLs, destroyed entities) and calling
onDestroy()before discarding them.
Queried components
| Component | Access |
|---|---|
ScriptComponent | Read (entries, defaultData, runtimeData) |
Behaviour resolution
The system resolves the Behaviour constructor from the imported module using:
- Named export matching
ScriptEntry.className. defaultexport as a fallback.- A
__reluBehaviourClassstatic marker check to handle cases where esbuild bundles a second copy of@relu-interactives/spatial-ecsinto the script blob (breaking theinstanceofidentity check).
If no valid Behaviour subclass is found, the entry goes to "error" with the message Failed to load script: Missing Behaviour export ... and the error is reported with phase "load".
Behavior notes
- Instance keying: each script instance is keyed by
entityId + scriptUrl + className. A new instance is created only when any of these three values changes. - Error isolation: errors thrown inside
init()oronUpdate()are caught per-instance. A failing script does not crash the frame loop or affect other scripts. The entry'sruntimeStatebecomes"error"andruntimeMessageholds the message. - One log per distinct error: the first occurrence of an error is logged with
console.error(entity name and id, class, phase) and delivered toworld.onScriptErrorlisteners. Repeats of the same error are not logged again. - Retry backoff: after a load,
init()oronUpdate()error the system waitsDEFAULT_SCRIPT_ERROR_RETRY_DELAY(1 s of world time) before it re-initialises the script. Pass{ errorRetryDelay }as the third constructor argument to change it. Disabling and re-enabling the entry retries at once. - Destroyed entity cleanup: when an entity is removed from the world, all of its script instances are destroyed and removed from the registry on the next update.
- Editor vs preview: Behaviours execute only at preview/runtime. In an editor world (
isEditorMode()), everyScriptComponententry stays inidlestate andinit()/onUpdate()never run. For visuals that must render in the editor, useScriptObjectSystem+ScriptObject.
API reference
- Class:
ScriptComponent - Base class:
Behaviour - Source:
core/systems/ScriptBehaviourSystem.ts

