Skip to content

Persistable

Updated

Saves the entity’s state so it is kept between sessions.

Type
ent-persistable
Script class
PersistableEntity

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:

  • storage picks which of the service’s two stores keeps the record, 'memory' or 'disk'. A new Persistable entity uses 'disk'.
  • retention is 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.
  1. Add a Persistable entity to the scene (see Scenes and hierarchy) and give it a clear name, such as Visits or Guest Book. Scripts find it by that name.
  2. Leave storage on 'disk', and set retention to how long unused data should be kept.
  3. To hear changes, including those other visitors make, add a Signal Emitter to the same entity and set its signal, for example visits.
  4. Add a Behavior script that finds the entity, gets its PersistableComponent and reads or writes values.
  5. Enter play to try it. Use one Persistable per kind of data, so unrelated features never write to the same record.

Add one to a stored counter each time the scene starts, and show the total on a label.

VisitCounter.jx
#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

  • startup is async, so it can await the service’s answers.
  • inc('count', 1) adds one to the stored number and resolves to the whole stored state after the change, so state.count is the new total.
  • Writes reject when the service refuses or cannot be reached. The catch falls back to get('count', 0), which never rejects: it returns the default when the key is missing or the request fails.

Count likes from every visitor, and update the display live when anyone presses the button.

LikeButton.jx
#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::change carries the stored state after the change in data.values, whether this visitor or another one made it. A change from another visitor also has data.origin set to 'remote'.
  • The button’s own Signal Emitter sends UIButton::press on likes/press; the script checks eventType because an emitter without a filter forwards every event of its entity.
  • The script never updates the label after its own write: the change event does it, so local and remote likes take the same path.

Store which levers are pulled, restore them when the scene loads, and let a button reset the puzzle.

LeverPuzzle.jx
#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: arrPull removes every occurrence of a value, arrPush appends one. Each write sends Persistable::change with the new state, and showLevers turns every lever to match.
  • clear() empties the record and sends Persistable::cleared to every listening visitor, so all levers go back up everywhere.
  • setRotation turns 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 in try/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.Vector3 are 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 with unlock() in a finally block. The Persistence guide shows the full pattern.

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-persistable 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

With a Signal Emitter on the entity, these events reach scripts as { entityId, eventType, data }. Compare eventType with the EventType constants.

  • Persistable::change
  • Persistable::cleared
  • Persistable::error

Like every entity, it also reports: Transform::change (and position-change, rotation-change, scale-change), Enable::change, Layer::change and Lock::change.

Run it in the browser, read its scripts, and download it as an XR Creator project.

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.

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