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.
Before you start
Section titled “Before you start”- 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
Networkuses for entities. See Networkable. - You can write a Behavior with
#pragma lifecycle(startup)andon(...). See Scripting.
The session
Section titled “The session”| Member | What it is |
|---|---|
Network. |
Whether this peer is in a room now. |
Network.room |
The room this peer is in, or joins next. |
Network. |
This peer’s id in the room; '' while not connected. |
Network.peers |
The other peers’ ids, oldest first, as a copy. |
Network. |
How many other peers there are, without making the copy. |
Network. |
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. |
Joining and leaving
Section titled “Joining and leaving”| Member | What it does |
|---|---|
Network. |
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. |
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().
Sharing objects
Section titled “Sharing objects”| Member | What it does |
|---|---|
Network. |
Share an entity, adding its Networkable when missing, or a plain object named by options.key. Returns its handle. |
Network. |
Stop sharing it; it stays here as it is. For an entity, its Networkable is removed. |
Network. |
The handle of a shared object, or of the shared object it is nested in; undefined when there is none. |
Network. |
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. |
Build a defined kind here and on every peer; this peer owns it. Returns its handle. |
Options
Section titled “Options”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, include. 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. |
destroy |
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.
Handles
Section titled “Handles”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. |
request |
Ask to simulate it, with what it is nested in; resolves whether this peer owns it now. |
release |
Hand it to another peer. |
add |
Replicate one more trait. |
add |
Replicate a value of your own. |
remove |
Stop replicating a trait. |
set |
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. |
set |
Move it to another partition for everyone. Only its owner can. |
An entity reports ownership through its Signal Emitter instead, with Networkable::ownership-change.
Trait rules
Section titled “Trait rules”- Built-in traits.
transformis the position, rotation and scale relative to the parent, and which parent it is under, so re-parenting an object is replicated with it.rigidbodyis 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.
NetworkTraitTypenames them all:NetworkTraitType.PointLight,NetworkTraitType.UISlider, and so on. The full list is on Networkable. - Entity traits are components. On an entity,
addTrait,removeTraitandsetTraitsadd, 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, andsetTraitskeeps it. - What is refused. On a plain object, a name that is not
transform,rigidbodyor a custom trait throws. On an entity, an unknown trait plays without it, with a warning.
Plain objects and spawned kinds
Section titled “Plain objects and spawned kinds”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
startupon every peer and replicate it with the samekey. 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 callNetwork.spawn(kind, data). Arena tells every other peer to runbuild(data). Every peer must rundefinebefore a spawn of that kind arrives, so put it instartup.
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.
Partitions
Section titled “Partitions”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. |
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. |
Stop seeing partition, unless a loaded scene or another script still does. |
Connection events
Section titled “Connection events”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, peer: 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- |
{ peerId }: another peer arrived. |
Networkable::peer- |
{ peer: another peer left. |
Networkable::ownership- |
{ is: this entity’s own ownership changed. |
The details of each are on Networkable.
Examples
Section titled “Examples”1. Reading the session
Section titled “1. Reading the session”#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(); } });}A UI Label shows the room and how many others are in it, refreshed on the Networkable’s connect, disconnect, join and leave events.
Read the label. The preview plays alone; in a published world it names the room and counts the people in it.
refreshreads 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.
Snippets
Section titled “Snippets”1. Replicating an entity with options
Section titled “1. Replicating an entity with options”#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' }); }}replicateadds a Networkable and its Networkable Traits when the crate has none.- Checking
isOwnerbeforesetPositionkeeps every peer from moving the crate at once. startupisasync, so it mayawaitthe ownership request.
2. A plain object shared by key
Section titled “2. A plain object shared by key”#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
colorcustom trait carries a value no component holds.
3. Spawning projectiles for everyone
Section titled “3. Spawning projectiles for everyone”#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 }, ); });}defineruns on every peer;spawnruns only on the peer that pressed the button, which owns the new spark.datatravels with the spawn, so every peer builds the spark with the same colour and position.ttl: 4removes each spark after four seconds, anddestroyWithOwnerremoves it if its owner leaves first.- The geometry is shared by every spark, since a removed copy is not disposed.
4. Moving to another room
Section titled “4. Moving to another room”#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'); } });}connectwith a room name leaves the current room and joins the new one; it resolvesfalseafter five seconds without success.- Errors also arrive on the Networkable’s signal, with a
messageyou can show.
5. Interest centred on the player
Section titled “5. Interest centred on the player”#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');}interestCenteronly 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.
Common mistakes
Section titled “Common mistakes”- Defining a kind too late. A spawn that arrives before
Network.defineran cannot be built. Define every kind instartup. - 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
updateon every peer fights the incoming state. Guard the motion withif (!net.isOwner) return;. - Unknown trait names on plain objects. Only
transform,rigidbodyand custom traits (withgetandset) work on a plain object; anything else throws. - Treating
peersas live.Network.peersis a copy taken when you read it. Read it again after a join or leave event.