ItemScript

ItemScript is a script that runs within an item. The most basic usage of ItemScript is to capture player actions or changes in the surrounding environment using $.onXXXX, and then describe the item’s own behavior in response.

An ItemScript that plays a sound when interacted with:

const sfx = $.audio("sfx1");

$.onInteract(() => {
  sfx.play();
});

Additionally, $.onUpdate is called frequently (usually more than 20 FPS) even if no changes occur.

An ItemScript that moves at a constant speed:

$.onStart(() => {
  $.state.pos = $.getPosition();
});

$.onUpdate(dt => {
  const newPos = $.state.pos;
  newPos.x += dt;

  $.setPosition(newPos);
  $.state.pos = newPos;
});

The functions passed to $.onXXXX are called callbacks.

$.onXXXX can generally be divided into three types:

  • Those that capture player actions or external changes: onUse, onInteract, onCollide, onReceive, etc.
  • Those called at fixed intervals: onStart, onUpdate, etc.
  • Those called when a time-consuming process is completed: onExternalCallEnd, onTextInput, etc.

In this way, you can describe autonomous objects or NPCs even with just a single item.

$.state

Due to technical reasons, ItemScript cannot persistently store values in variables or memory. Memory is guaranteed to be retained during the execution of a single callback, but between multiple callback executions, you must assume that the memory may be cleared. In such cases, you can use $.state to retain state.

Example that does not work:

let x = 0;
$.onUpdate(dt => {
    x += dt;
    $.setPosition(new Vector3(x, 0, 0));
});

Example that works:

$.onStart(() => {
    $.state.x = 0;
});

$.onUpdate(dt => {
    $.state.x = $.state.x + dt;
    $.setPosition(new Vector3($.state.x, 0, 0));
});

ItemScript configuration and execution order

ItemScript is assigned to either world-placed items or item templates. (In other words, it is not possible to execute different ItemScripts for items generated from the same item template.)

When an item is generated within a space instance (for world-placed items, this happens immediately after the space instance is created), an ItemScript starts independently for each item. The processing is executed in the following order:

  1. (Item generation)
  2. onStart
  3. Other callbacks (onUse, onUpdate, etc.)
  4. (Item destruction)

Internal behavior of ItemScript

Like the items themselves, ItemScripts are executed by the Owner. To enable speculative execution, the script itself is loaded and evaluated on all devices after the item is generated. However, callbacks are executed only on the device of the current owner and the devices expected to become the owner.