Skip to content

Network

Updated

Network is the script global for multiplayer. It tells you about the session (are you in a room, who else is there), joins and leaves rooms, and shares objects from code: an entity, a plain object, or a kind of object every peer knows how to build. For each object you choose which traits travel: its transform, its velocities, a component’s props, or a value of your own. Without a room, every call still works and everything stays local, so the same script runs alone and with others.

  • You know what a room, a peer, an owner and a trait are. See the Multiplayer overview.
  • You know the Networkable and Networkable Trait components, which Network uses for entities. See Networkable.
  • You can write a Behavior with #pragma lifecycle(startup) and on(...). See Scripting.
Member What it is
Network.connected Whether this peer is in a room now.
Network.room The room this peer is in, or joins next.
Network.peerId This peer’s id in the room; '' while not connected.
Network.peers The other peers’ ids, oldest first, as a copy.
Network.peerCount How many other peers there are, without making the copy.
Network.interestCenter What spatial interest is centred on, such as the player’s avatar: an entity or a plain object in the scene. Unset, the active camera. Cleared when the script that set it is released.
Member What it does
Network.connect(room?, { timeout? }) Join room now, by default the current one: after disconnect(), or to move to another room. Resolves true once in, false when the attempt fails within timeout seconds (15 by default).
Network.disconnect() Leave the room and stay out until connect(). Every object is simply local meanwhile.

When the project has networking on, a scene joins while it loads, so its scripts start already in the room. With it off, objects stay local until a script calls Network.connect(). Once joined, a dropped connection comes back on its own; disconnect() stops that until the next connect().

Member What it does
Network.replicate(object, options?) Share an entity, adding its Networkable when missing, or a plain object named by options.key. Returns its handle.
Network.unreplicate(object) Stop sharing it; it stays here as it is. For an entity, its Networkable is removed.
Network.of(object) The handle of a shared object, or of the shared object it is nested in; undefined when there is none.
Network.define(kind, build, setup?) Teach this peer how to build kind: build(data) returns the object and puts it in the scene; setup(handle, data), run on every peer, declares its custom traits.
Network.spawn(kind, data?, options?) Build a defined kind here and on every peer; this peer owns it. Returns its handle.

replicate and spawn take:

Option What it sets
key The name that identifies a plain object on every peer. Required for one; ignored for an entity, which its id names.
traits What to replicate: trait names, or entries such as { type, frequency, includeScale }. The default is transform. For an entity these become its Networkable Traits.
ownership 'transfer' (anyone may take it, the default) or 'locked' (only its first owner simulates it, such as a player avatar).
persistent Keep it in the room after everyone leaves. true by default for an entity.
destroyWithOwner Remove it when its owner leaves, rather than handing it to another peer: avatars, projectiles.
ttl Remove it this many seconds after it appears, up to 30 days; 0 keeps it.
idle Remove it after this many seconds nobody updates or uses it; 0 is a day (the default), 30 days at most.
partition The partition a plain object or a spawned kind belongs to, instead of its scene’s. '' is the whole room. Ignored for an entity, which belongs to its scene.

A trait frequency is 'high' (20 times a second), 'medium' (10), 'low' (2) or 'auto', the trait’s own rate. A trait is sent only when it changed.

A handle is what replicate, of and spawn return: an entity’s NetworkableComponent, or a plain object’s network object. Both have:

Member What it does
isOwner Whether this peer simulates it: its owner, or it is not shared yet. Only the owner’s changes are sent.
isProxy Whether it is a copy driven by another peer.
ownerId The owning peer’s id; '' while it is not shared.
requestOwnership() Ask to simulate it, with what it is nested in; resolves whether this peer owns it now.
releaseOwnership() Hand it to another peer.
addTrait(type, frequency) Replicate one more trait.
addTrait(name, { get, set, frequency? }) Replicate a value of your own.
removeTrait(type) Stop replicating a trait.
setTraits(list) Replicate exactly these traits.
destroy() Remove it for everyone, as its owner.

A plain object’s handle also has:

Member What it does
onOwnerChange A function you assign, called with isOwner each time this peer gains or loses it.
traits The trait names it replicates.
partition The partition a script gave it.
setPartition(partition) Move it to another partition for everyone. Only its owner can.

An entity reports ownership through its Signal Emitter instead, with Networkable::ownership-change.

  • Built-in traits. transform is the position, rotation and scale relative to the parent, and which parent it is under, so re-parenting an object is replicated with it. rigidbody is the linear and angular velocity.
  • Component traits. On an entity, a component that supports it replicates its props and whether it is on, under its trait name. NetworkTraitType names them all: NetworkTraitType.PointLight, NetworkTraitType.UISlider, and so on. The full list is on Networkable.
  • Entity traits are components. On an entity, addTrait, removeTrait and setTraits add, change and remove Networkable Trait components, which are saved with the scene.
  • Custom traits. addTrait(name, { get, set }) replicates your own value: get() is read on the owner and sent when it changed, set(value) is called on every other peer. A value is a number, a string, a boolean or a small array of them. A custom trait is never saved, and setTraits keeps it.
  • What is refused. On a plain object, a name that is not transform, rigidbody or a custom trait throws. On an entity, an unknown trait plays without it, with a warning.

There are two ways to share something that is not an entity of the scene:

  • Every peer builds it the same way. Build the object in startup on every peer and replicate it with the same key. The key is how the peers agree it is the same object.
  • One peer creates it. Teach every peer the recipe with Network.define(kind, build), then let one peer call Network.spawn(kind, data). Arena tells every other peer to run build(data). Every peer must run define before a spawn of that kind arrives, so put it in startup.

When a spawned copy goes, it is removed, not disposed. Share geometries and materials between copies, or free them yourself.

Plain objects a script replicates, kinds it defines and objects it spawns stop replicating when the script is released.

Every shared object belongs to a partition, and a peer only receives the objects of the partitions it sees. An entity’s partition is its scene; a peer sees the scenes it has loaded. A plain object or a spawned kind can name its own partition with the partition option, to group objects freely, for example the wings of one building.

Member What it does
Network.subscribe(partition) See the objects of partition too, beyond those of the loaded scenes. Held until unsubscribe or until the script is released. A name is at most 256 characters, and a peer sees at most 64 partitions, its loaded scenes first.
Network.unsubscribe(partition) Stop seeing partition, unless a loaded scene or another script still does.

Joining, leaving, errors and other peers are reported by every Networkable through its Signal Emitter. Put a Signal Emitter on one Networkable in the scene and listen to its signal:

Event Data
Networkable::connect { room, peerId }: this peer joined the room.
Networkable::disconnect { room, reason }: 'left', 'lost', or 'kicked', 'banned', 'room-closed' when the room removed this peer.
Networkable::error { room, message, code?, retrying }: an attempt to join failed.
Networkable::peer-join { peerId }: another peer arrived.
Networkable::peer-leave { peerId, reason? }: another peer left.
Networkable::ownership-change { isOwner, ownerId }: this entity’s own ownership changed.

The details of each are on Networkable.

WhoIsHere.jx
#pragma lifecycle(startup)
let status;
function refresh() {
if (!Network.connected) {
status.setProps({ text: 'Playing alone' });
return;
}
status.setProps({ text: `Room ${Network.room}: you and ${Network.peerCount} others` });
}
function startup() {
status = findEntity('Status').getComponent(UILabelComponent);
refresh();
on('net', (event) => {
if (
event.eventType === EventType.Networkable.Connect ||
event.eventType === EventType.Networkable.Disconnect ||
event.eventType === EventType.Networkable.PeerJoin ||
event.eventType === EventType.Networkable.PeerLeave
) {
refresh();
}
});
}
  • refresh reads the session members directly; there is nothing to cache.
  • The label updates on each connection or peer event, and once at startup for the join that came before it.
SharedCrate.jx
#pragma lifecycle(startup)
// Scene: a "Crate" with a dynamic rigid body and a Standard Material.
async function startup() {
const crate = findEntity('Crate');
const net = Network.replicate(crate, {
traits: [
NetworkTraitType.Transform,
NetworkTraitType.RigidBody,
{ type: NetworkTraitType.StandardMaterial, frequency: 'low' },
],
persistent: true,
});
// Only the owner places it; everyone else receives the position.
if (net.isOwner) crate.setPosition(0, 1, 0);
if (await net.requestOwnership()) {
crate.getComponent(MaterialComponent).setProps({ color: '#ff0000' });
}
}
  • replicate adds a Networkable and its Networkable Traits when the crate has none.
  • Checking isOwner before setPosition keeps every peer from moving the crate at once.
  • startup is async, so it may await the ownership request.
Orb.jx
#pragma lifecycle(startup, update)
// Every peer runs this script, so every peer builds the same orb.
let orb;
let net;
let angle = 0;
function startup() {
orb = new THREE.Mesh(
new THREE.SphereGeometry(0.2),
new THREE.MeshStandardMaterial({ color: 0x38bdf8 }),
);
orb.position.set(0, 1.5, 0);
scene.add(orb);
net = Network.replicate(orb, { key: 'orb', traits: [NetworkTraitType.Transform] });
net.onOwnerChange = (mine) => log(mine ? 'I move the orb' : 'Someone else moves the orb');
// A custom trait: the orb's colour as a number.
net.addTrait('color', {
get: () => orb.material.color.getHex(),
set: (value) => orb.material.color.setHex(value),
});
on('orb/recolor', () => {
if (net.isOwner) orb.material.color.setHex(Math.floor(Math.random() * 0xffffff));
});
}
function update(dt) {
if (!net.isOwner) return; // proxies follow the owner's transform
angle += dt;
orb.position.x = Math.cos(angle) * 2;
orb.position.z = Math.sin(angle) * 2;
}
  • The key 'orb' is the same on every peer, so the room treats the meshes as one object.
  • Only the owner animates the orb in update; the others receive its transform.
  • The color custom trait carries a value no component holds.
Sparks.jx
#pragma lifecycle(startup)
// Scene: a UI Button with a Signal Emitter on 'fire'.
const sparkGeometry = new THREE.SphereGeometry(0.05);
function startup() {
// Every peer must know the recipe before a spawn arrives.
Network.define('spark', (data) => {
const spark = new THREE.Mesh(sparkGeometry, new THREE.MeshBasicMaterial({ color: data.color }));
spark.position.set(data.x, 1.5, 0);
scene.add(spark);
return spark;
});
on('fire', (event) => {
if (event.eventType !== EventType.UIButton.Press) return;
Network.spawn(
'spark',
{ color: 0xffaa00, x: (Math.random() - 0.5) * 4 },
{ ttl: 4, destroyWithOwner: true },
);
});
}
  • define runs on every peer; spawn runs only on the peer that pressed the button, which owns the new spark.
  • data travels with the spawn, so every peer builds the spark with the same colour and position.
  • ttl: 4 removes each spark after four seconds, and destroyWithOwner removes it if its owner leaves first.
  • The geometry is shared by every spark, since a removed copy is not disposed.
RoomSwitch.jx
#pragma lifecycle(startup)
// Scene: a UI Button with a Signal Emitter on 'go/arena-2', and a Networkable
// with a Signal Emitter on 'net'.
function startup() {
on('net', (event) => {
if (event.eventType === EventType.Networkable.Error) {
log('Network error:', event.data.message);
}
});
on('go/arena-2', async (event) => {
if (event.eventType !== EventType.UIButton.Press) return;
if (await Network.connect('arena-2', { timeout: 5 })) {
log(`Now in ${Network.room} as ${Network.peerId}`);
} else {
log('Could not join arena-2');
}
});
}
  • connect with a room name leaves the current room and joins the new one; it resolves false after five seconds without success.
  • Errors also arrive on the Networkable’s signal, with a message you can show.
FollowPlayer.jx
#pragma lifecycle(startup)
// Scene: an "Avatar Template" entity, disabled, used as the player's body.
function startup() {
const avatar = spawn('Avatar Template', { enabled: true });
// With spatial interest on, receive what is near the avatar rather than the camera.
Network.interestCenter = avatar;
// See the objects of an extra partition, such as a shared lobby.
Network.subscribe('lobby');
}
  • interestCenter only matters when the project has spatial interest on; otherwise every object of the visible partitions is received.
  • The subscription to 'lobby' is released automatically with the script.
  • Defining a kind too late. A spawn that arrives before Network.define ran cannot be built. Define every kind in startup.
  • Different keys on different peers. A plain object is matched by its key. A key built from something random or local (Math.random(), the peer id) makes each peer share a different object.
  • Animating proxies. Moving an object in update on every peer fights the incoming state. Guard the motion with if (!net.isOwner) return;.
  • Unknown trait names on plain objects. Only transform, rigidbody and custom traits (with get and set) work on a plain object; anything else throws.
  • Treating peers as live. Network.peers is a copy taken when you read it. Read it again after a join or leave event.