Persistable
Updated
Saves the entity’s state so it is kept between sessions.
- Type
ent-persistable- Script class
PersistableEntity- Family
- Logic and AI
Overview
Section titled “Overview”A Persistable is an invisible entity that stores data for your world on a persistence service, so the data is still there after a reload, the next day, or in a new session. Typical uses are a visit counter, a guest book, a high score, a “like” button or the solved state of a puzzle. It draws nothing and has no position: it only holds a record, a set of values under string keys, like the fields of a JSON object.
The record is keyed by the entity’s id, which is saved with the scene. That has two consequences:
- The data comes back. Reload the scene and the same entity finds the same record.
- The data is shared. Every visitor whose copy of the scene holds this entity reads and writes the same record, so a counter one visitor increments goes up for everyone.
Scripts read and write the record through the entity’s Persistable component (PersistableComponent). Every call goes to the service and returns a promise: a value that arrives later, which you wait for with await inside an async function. With a Signal Emitter on the entity, the Persistable also reports each change as an event, including changes other visitors make.
Persistable or Networkable? Use a Persistable for data that must outlive the session, whoever is connected. To share live, moment-to-moment state with the people in the room now, such as a moving object or a switch, use a Networkable instead. Many worlds use both: a Networkable for the live game and a Persistable for the high score.
The props that matter most:
storagepicks which of the service’s two stores keeps the record,'memory'or'disk'. A new Persistable entity uses'disk'.retentionis how long the record is kept after it was last used, in minutes, from 60 (one hour) to 43 200 (30 days). Each successful read or write renews it. A new Persistable entity uses 10 080, which is seven days.
Set it up
Section titled “Set it up”- Add a Persistable entity to the scene (see Scenes and hierarchy) and give it a clear name, such as
VisitsorGuest Book. Scripts find it by that name. - Leave
storageon'disk', and setretentionto how long unused data should be kept. - To hear changes, including those other visitors make, add a Signal Emitter to the same entity and set its
signal, for examplevisits. - Add a Behavior script that finds the entity, gets its
PersistableComponentand reads or writes values. - Enter play to try it. Use one Persistable per kind of data, so unrelated features never write to the same record.
Examples
Section titled “Examples”Count visits
Section titled “Count visits”Add one to a stored counter each time the scene starts, and show the total on a label.
#pragma lifecycle(startup)
// Scene: a Persistable entity named "Visits" and a UI Label named "Visit Count".async function startup() { const store = findEntity('Visits').getComponent(PersistableComponent); const label = findEntity('Visit Count').getComponent(UILabelComponent);
try { const state = await store.inc('count', 1); label.setProps({ text: `Visit number ${state.count}` }); } catch (error) { const count = await store.get('count', 0); label.setProps({ text: `Visits: ${count}` }); }}How it works
startupisasync, so it canawaitthe service’s answers.inc('count', 1)adds one to the stored number and resolves to the whole stored state after the change, sostate.countis the new total.- Writes reject when the service refuses or cannot be reached. The
catchfalls back toget('count', 0), which never rejects: it returns the default when the key is missing or the request fails.
A shared like button
Section titled “A shared like button”Count likes from every visitor, and update the display live when anyone presses the button.
#pragma lifecycle(startup)
// Scene: a Persistable entity named "Likes" with a Signal Emitter on 'likes',// a UI Button with a Signal Emitter on 'likes/press', and a UI Label named "Like Count".let store;let label;
function show(count) { label.setProps({ text: `${count ?? 0} likes` });}
async function startup() { store = findEntity('Likes').getComponent(PersistableComponent); label = findEntity('Like Count').getComponent(UILabelComponent); show(await store.get('count', 0));
// Our own writes and other visitors' writes both arrive here. on('likes', (event) => { if (event.eventType === EventType.Persistable.Change) show(event.data.values?.count); if (event.eventType === EventType.Persistable.Error) log('Likes:', event.data.message); });
on('likes/press', async (event) => { if (event.eventType !== EventType.UIButton.Press) return; try { await store.inc('count', 1); } catch (error) { log('Could not save the like'); } });}How it works
- The label is filled once at startup with
get, then kept current by events. - The Signal Emitter on the Persistable puts its events on
likes.Persistable::changecarries the stored state after the change indata.values, whether this visitor or another one made it. A change from another visitor also hasdata.originset to'remote'. - The button’s own Signal Emitter sends
UIButton::pressonlikes/press; the script checkseventTypebecause an emitter without a filter forwards every event of its entity. - The script never updates the label after its own write: the
changeevent does it, so local and remote likes take the same path.
Remember a solved puzzle
Section titled “Remember a solved puzzle”Store which levers are pulled, restore them when the scene loads, and let a button reset the puzzle.
#pragma lifecycle(startup)
// Scene: a Persistable entity named "Puzzle" with a Signal Emitter on 'puzzle'.// Three lever entities named "Lever 1" to "Lever 3", each with a Selectable and a// Signal Emitter on 'puzzle/lever', and a UI Button with a Signal Emitter on 'puzzle/reset'.const NAMES = ['Lever 1', 'Lever 2', 'Lever 3'];let store;
function showLevers(pulled) { for (const name of NAMES) { const lever = findEntity(name); const down = (pulled ?? []).includes(name); lever.setRotation(down ? DEG_TO_RAD(-45) : 0, 0, 0); }}
async function startup() { store = findEntity('Puzzle').getComponent(PersistableComponent); showLevers(await store.get('pulled', []));
on('puzzle', (event) => { if (event.eventType === EventType.Persistable.Change) showLevers(event.data.values?.pulled); if (event.eventType === EventType.Persistable.Cleared) showLevers([]); });
on('puzzle/lever', async (event) => { if (event.eventType !== EventType.Selectable.Select) return; findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again const name = findEntity(event.entityId).name; const pulled = await store.get('pulled', []); try { if (pulled.includes(name)) await store.arrPull('pulled', name); else await store.arrPush('pulled', name); } catch (error) { log('Could not save the lever'); } });
on('puzzle/reset', async (event) => { if (event.eventType !== EventType.UIButton.Press) return; await store.clear(); });}How it works
- The record holds one array,
pulled, with the names of the levers that are down.get('pulled', [])returns an empty array the first time. - Clicking a lever toggles its name in the array:
arrPullremoves every occurrence of a value,arrPushappends one. Each write sendsPersistable::changewith the new state, andshowLeversturns every lever to match. clear()empties the record and sendsPersistable::clearedto every listening visitor, so all levers go back up everywhere.setRotationturns each lever with its colliders, so it stays clickable where it is drawn.
- Every call returns a promise. Without
await, you hold the promise, not the value. Wrap writes intry/catch: a rejected write that nobody catches stops the script. - Store only JSON values: numbers, strings, booleans, arrays and plain objects. Functions and class instances such as a
THREE.Vector3are not stored; save{ x, y, z }instead.
- When two visitors may write at the same moment, such as when comparing and saving a high score, take the record with
lock(timeout)first and release it withunlock()in afinallyblock. The Persistence guide shows the full pattern.
Components
Section titled “Components”What a new Persistable is made of. Required components are always present and cannot be removed; the others can. Per entity says whether an entity can hold one of that component or several. Layer, Lock and Enable are on every placed entity, and Transform holds its position, rotation and scale.
| Component | Type | Role | Per entity | What it does |
|---|---|---|---|---|
| Layer | comp-layer |
Required | One | Puts the entity on a render/raycast layer so cameras and rays can include or skip it. |
| Lock | comp-lock |
Required | One | Editor-only flag that stops the entity from being selected or moved. |
| Enable | comp-enable |
Required | One | Turns the entity and its children on or off: hides them and stops their behavior. |
| Persistable | comp- |
Required | One | Saves the entity’s state so it is kept between sessions. |
You can also add 5 optional components, such as Animation Graph, Animation Timeline, Dont Unload, Motion Path Controller, Signal Emitter.
The settings of a new entity, as the runtime creates it. Change them in the Properties panel of XR Creator, or from a script with getComponent(…).setProps({ … }).
| Prop | Default | Range |
|---|---|---|
enabled |
true |
|
storage |
"disk" |
|
retention |
10080 |
60 ≤ x ≤ 43200 |
Events
Section titled “Events”With a Signal Emitter on the entity, these events reach scripts as { entityId, eventType, data }. Compare eventType with the EventType constants.
Persistable::changePersistable::clearedPersistable::error
Like every entity, it also reports: Transform::change (and position-change, rotation-change, scale-change), Enable::change, Layer::change and Lock::change.
Live example
Section titled “Live example”Run it in the browser, read its scripts, and download it as an XR Creator project.
A Persistable adds one to a stored count each time the scene starts, with inc, and a UI Label shows the total, or the last known value when the write fails.
Read the label, then run the example again. Without the persistence service the write fails and the label shows the offline value.
From a script
Section titled “From a script”Find the entity by its name, check its class, and work with its components. Name the entity in the Hierarchy first; this example expects My Persistable.
#pragma lifecycle(startup)
function startup() { // Find the entity by the name it has in the Hierarchy. const entity = findEntity('My Persistable'); if (!(entity instanceof PersistableEntity)) return;
// Its Persistable component holds the settings listed under Props. const component = entity.getComponent(PersistableComponent); log('retention is', component.props.retention); component.setProps({ retention: 15120 });}