Log inGet started

Multiplayer

Updated December 4, 2026

What syncs, and when

The two modes share differently (edit vs play is the engine guide):

  • In edit mode, the world itself syncs. Source content and the entities you place propagate to everyone connected — editing is collaborative, like a shared document. This is why there's no "save and send": writing to /zero/source is sharing it.
  • In play mode, gameplay runs per peer, and only fields you mark for replication sync. Each component field is declared with a replication mode, and only Sync fields cross the wire during play.
public = {
  health   = Field.number(100, Sync),    -- replicated to all peers during play
  _vfxSeed = Field.number(0,   NoSync),  -- local-only; stays on this peer
}

Sync / NoSync is the mode every Field.<kind> takes, after the kind's own arguments and before its description (the components guide covers fields; the authoring guide says what each kind takes). A component replicates at most 247 Sync fields, its public and private ones together: adding a component that declares more raises an error naming the component and the limit.

A value that changes every frame (a throttle, an rpm, a light's state) is a named value rather than a field (the topics/values guide): it replicates nothing until it is declared to, and a declaration names the rate it travels at, so the owner sends it at most that often and always its newest value: car.values.declare("throttle", { type = "number", replicate = 10 }). Choosing per field is the whole replication design: shared game state is Sync; cosmetic or per-peer scratch is NoSync. A component's private fields take the same argument and replicate the same way when Sync; the only difference is that a private field routes to the private table on every peer instead of the inspector-visible one (the components guide covers the private surface).

A value crossing the wire (a Sync field, a declare.syncedFunctions argument, a Sync event payload, a multiplayer.send argument) arrives as what it is: an entity or component proxy as the receiving peer's own, a vector as a vector, and a table as a table of the same values, with the proxies and vectors nested in it carried the same way. /zero/docs/api/globals/multiplayer/send states the whole rule, the keys a table arrives with included.

A field holding a table (Field.table, Field.vec3, a struct or list) answers a read with that table, and a change made in it is a change to the field: public.inventory.coins += 1 replicates the way public.inventory = t does. The same holds for the table a walk of the component (for k, v in comp) hands out and for a table assigned to the field and still held by the code that assigned it. The engine judges such a change at the end of the frame it was made in, as the assignment of the field it stands for: on an entity this peer owns it is sent; on a synced entity another peer owns the table is put back as it was and the log carries the same only the owner may mutate a synced entity refusal an assignment gets. A table kept from an earlier frame stays judged for as long as the field holds it, by who owns the entity in the frame the change is made in.

Joining: the scene materializes first

A peer that joins a play session receives the current scene as a snapshot before its gameplay starts. While that snapshot is still arriving, gameplay simulation is held — component update(dt) / fixedUpdate(dt), physics, and hooks don't run — so a freshly-joined character can't fall through ground that hasn't streamed in yet. Once the snapshot lands, simulation resumes and the character settles onto the now-present scene.

engine.gameplayReady reports this: it is true when gameplay is simulating (and false while a joiner's scene is still materializing, or in edit mode). If your update() isn't firing in play mode, read it: gameplayReady == false with engine.paused == false means the scene is still materializing. The same per-frame state reaches you as state.gameplayReady on the execute responses whose state block carries the snapshot; a response reading state: {unchanged: true} is saying the last snapshot you were handed still stands.

Entities: who owns what

Entities carry an owner, and you decide which ones replicate at all:

local e = entity(id)
e.setSynced(true)     -- this entity participates in multiplayer
e.synced()            -- boolean
e.isLocal()           -- does this peer own it?
e.owner()             -- owning peer id (0 = unowned / server)

The owner is the peer that simulates an entity; other peers receive its synced state. When ownership matters at runtime (picking up an object, taking control of a vehicle), the multiplayer namespace handles it:

multiplayer.isOwner(id)
multiplayer.claimOwnership(id)
multiplayer.releaseOwnership(id)

The relay holds every peer to the owner it records. A claim takes an entity no peer owns: one never claimed, or one its owner released. An entity another peer owns stays theirs, whoever asks: the claim is refused, and so is any change to it from another peer (a despawn, a component added or removed, a synced value written). To hand an entity on, its owner releases it and the next peer to claim it takes it; ask the owner for it the way your game talks between peers (an RPC or a synced field), and have the owner's code release it. A refusal changes nothing anywhere and reaches no other peer; it is logged, multiplayer.getDiagnostics().refusals counts it, and lastRefusal names the latest.

Author so that the owning peer drives logic and everyone else reflects it — a common shape is "only act on entities where isLocal() is true."

Ownership is established when a peer announces an entity to its room, and the room keeps one owner per entity. A peer announces an entity into a room once the room has answered its join, and that answer delivers every entity the room already holds, each under the owner the room records. A scene's synced entities are built by every peer that loads the scene, under one id: in play the first peer to announce one owns it, and a peer whose room already holds it receives it under that owner and sends nothing for it, so every peer reads the same owner() and the owner alone writes it. A departure hands the leaver's entities to the room's host, the peer that holds the room's simulation (multiplayer.roomHost(key) names it, and multiplayer.isHost() answers true there): the room's first peer, until a person's own client in a room an agent's sub-client hosts has loaded the scene and takes the host over with the persistent entities the sub-client owned, and a departing host hands the room to a person's client before a sub-client. A client that joins a hosted room reads multiplayer.isHost() false through its scene's load, its components' start included, even when the host leaves during that load and the room names it the successor, so a world spawned at start behind isHost() is spawned once in the room. So a peer that leaves a room and joins it again (a scene reload in play does both) writes nothing to the room's entities until the room answers the new join, which restates each one under the owner the room records then. In edit mode scene content is announced by no peer, so such an entity is unowned on every peer (owner() reads 0, isLocal() and isOwner read false everywhere) and each peer may change it: an edit to it is recorded in the scene like any authored entity, and a change one peer makes reaches the others once and is sent back by none of them.

Players and peers

Players are first-class and engine-spawned; the scene's root surfaces them (the scenes guide has the players registry — localPlayer, onJoin, onLeave). A player is the per-peer identity; its avatar is a separate physical entity — an ordinary synced entity that every peer sees, owned by the peer it belongs to and removed when that peer leaves. View concerns stay per-peer: each peer drives its OWN avatar and runs its own camera/input, gating controller logic on entity:isLocal() so a peer never moves another peer's avatar. For the raw session you also have:

world.participants()                         -- who's connected
world.on("player_join",  function(p) end)
world.on("player_leave", function(p) end)
multiplayer.getPeers()                        -- peer list
multiplayer.getPeerId()                       -- this peer's id

Messages between peers

multiplayer.send(channel, ...) broadcasts a message to every other peer in the room, and multiplayer.on(channel, callback) receives them as callback(fromPeerId, ...). multiplayer.on returns the function that stops its listener:

local stop = multiplayer.on("bell", function(from, bellId) ring(bellId) end)
-- when this code no longer wants the messages:
stop()

A listener also stops with the code that registered it, so code that runs again does not leave an earlier copy listening: a module's listener stops when the module is reloaded, a component's when its instance is destroyed or reloaded, a scene entrypoint's when its scene load ends. A module that registers its listeners as it loads therefore handles each message once however often it is reloaded. scopes.list() lists every live listener (multiplayerListener), with its channel and what it follows.

How another peer's bodies move on this peer

A synced entity has one peer simulating it, its owner, and every other peer draws it from the poses that peer sends: a car, a crate, a projectile and an avatar alike. The owner sends a pose each frame the entity moves, stamped with the session clock (below). A receiving peer draws the entity a short delay behind the newest pose it holds (0.1 s unless the world says otherwise), interpolated between the poses either side of that moment, so the entity moves a steady step every frame whatever the frame rate on either side and the jitter between them. A pose that arrives after a newer one lands in its place and never moves the entity back. When poses stop arriving the entity carries on along its last motion for a bounded time and then holds, and when they arrive again it catches up with them over the next frames (at most a quarter faster or slower than they move, plus 1 m/s, or the distance left over one second when that is more) rather than jumping to them, so a car another peer drives does not leap after a network hiccup. A body carried past its poses slows onto them, and steps back only when it stands farther ahead of them than they move in a second or they move slower than 4/3 m/s. A step faster than a body moves (a respawn, a reset to the start line) is a teleport and is drawn as a cut, however long the entity stood still before it; a moving body whose poses were lost on the way for a second or two, or whose owner stalled, is judged against anywhere between where it stood and where its motion carried it, so it is caught up with rather than cut. Another peer taking the entity over starts its motion over from that peer's first pose. The owner's own view is its simulation, untouched. A dynamic body another peer simulates is a kinematic body here that follows the drawn pose, so it still pushes what it drives into.

The world tunes it through its settings, and a peer per entity:

settings.set("sync.interpolation_delay", 0.15)   -- seconds behind the newest pose
settings.set("sync.extrapolation_limit", 0.25)   -- seconds to carry on once poses stop
settings.set("sync.teleport_speed", 150)         -- m/s above which a step is a cut
settings.set("sync.interpolation", false)        -- draw the newest pose as it arrives

multiplayer.setSmoothing(rocket, { delay = 0.05, teleportSpeed = 600 })
local s = multiplayer.smoothing(rocket)          -- the settings in effect, and its stream
print(s.delay, s.stream and s.stream.lag, s.stream and s.stream.stale)

A longer delay rides out more jitter and loss and shows the entity later; a fast sender (60 poses a second) is smooth at a short one, and a sender stating 20 a second wants at least 0.1 s. smoothing(e).stream says what this peer holds for the entity: the poses buffered, how far the newest is ahead of the moment drawn (lag, negative while it extrapolates), how far it is drawn from where its poses put it while it catches up with them after a gap (correction, metres), and the running counts of poses received, dropped as stale, stream restarts and teleports.

What a receiving peer draws, exactly: a moment on the session clock, the owner's now less the network transit less the delay. The transit is the fastest arrival this peer has seen in the last two seconds, and it stays in: one peer cannot measure the one-way time to another, so nothing takes it out. delay = 0 therefore draws the newest pose the network has delivered, carried along its motion between arrivals, and it still trails the owner by the transit. A game that wants another player's projectile drawn where its shooter sees it now leads it forward itself, by about half the round trip to the shooter (latency on the shooter's row of multiplayer.getPeers(), in milliseconds, measured out through the relay to that peer and back).

A body that stops dead is held where it stopped once a pose taken after the stop arrives: the owner states the pose it rests at about 0.1 s after it stops moving. At a delay shorter than that, a receiving peer carries the body on along its last motion until then (for at most the extrapolation limit) and then eases it back to where it stopped, so a rocket at a small delay is drawn a few metres into the wall it hit before it comes back out. State an impact as an event of its own (a synced field holding the hit point, or a message) rather than reading it off the rocket's last pose. A release keeps the entity's motion as it was, since the peer that released it still moves it; another peer taking it over starts its motion over from that peer's first pose.

A body that stood still and then turns or moves at once is drawn turned or moved within the delay, the way its owner made the change: the pose it stood at holds until the step into the next one.

Each peer builds and poses the entities under a synced entity on its own (a character's body, a vehicle's turret), so a pose the owner gives one of them stays on the owner's peer. Name such a child and its local position and rotation travel with the entity, drawn on every other peer on the timeline the entity is drawn on:

multiplayer.syncChildPose(self.entity, "turret")       -- every peer names it, in the component's start
if not multiplayer.childPoseFromOwner(turretId) then   -- true on a peer that draws it from its owner
    aimTurret()
end

The owner states the child each frame it changes, once more after it settles (which a peer joining later reads), and again every second while it stands. A peer draws from the owner only the children it names itself, and a child the owner stops naming is each peer's own to pose again. Locomotion names the child whose rotation is a character's facing, so another player's character faces where its owner turned it.

A synced entity riding another synced entity (a character on a moving deck, a passenger in a car, a crate on a ship) is drawn behind its own owner, and the body it rides behind that body's owner. Stated in the world, the rider slides across the body by the distance the body covers in those two delays. Name the body it rides, on the peer that owns the rider, and the rider's pose is stated in that body's space: every peer draws it where that peer draws the body, so it holds its spot there on every screen.

multiplayer.setPoseFrame(crate, ship)   -- the crate's owner names the ship it rides
print(multiplayer.poseFrame(crate))     -- the ship's id, on the owner and on every peer that draws it there
multiplayer.setPoseFrame(crate, nil)    -- stated in the world again

The frame can also be an entity under a synced body, such as the hand bone a held prop sits in. Every peer finds that entity under its own copy of the body by the names of the entities between, and draws the rider in it as that peer poses it, so a prop stays in the hand each peer animates while its holder walks. Holdable names the grip a held prop is seated in.

A CharacterController names the kinematic or dynamic body it stands on by itself, and keeps it through a jump until it lands.

Acting in step: the session clock

Each engine counts its own time, so a timestamp one engine takes means nothing to another. multiplayer.sessionTime() is the one timeline every participant of a session reads alike: seconds since the Unix epoch, placed on the relay's clock with the round trip to it taken out. To make peers act together, pick a moment on it a little in the future (enough for the message to arrive, half a second is plenty), share it, and let every peer work out where it is from there:

public = {
  startAt = Field.number(nil, Sync),  -- a session time every peer receives
}
local PERIOD = 2

-- The peer that starts it calls this: a countdown, a dance, a high five, a lightning strike.
local function begin()
  public.startAt = multiplayer.sessionTime() + 0.5
end

-- Every peer, every frame: the same answer everywhere.
function update(dt)
  if public.startAt == nil then return end
  local t = multiplayer.sessionTime() - public.startAt   -- negative until it starts
  local phase = (t % PERIOD) / PERIOD                    -- a looping effect in phase
  local hour = (multiplayer.sessionTime() / 60) % 24     -- a day/night cycle all peers share
end

An event or multiplayer.send carries the start time as well as a Sync field does.

ClipPlayer.startedAt takes such a time and plays its clip at the same clip time on every peer.

multiplayer.sessionClock() says how far to trust the reading: synced is true once the relay has answered (before that, and with no relay, the reading is this machine's own wall clock), and accuracyMs bounds how far it lies from the relay's clock, about half the round trip to the relay. Two peers agree to within the sum of their accuracyMs. The reading never runs backwards once synced: a correction makes it run up to 10% fast or slow until it is worked off, and it jumps forward only when it trails by more than a quarter second. It keeps counting across a re-dial, a world swap and a tab the browser held in the background, re-asks the relay at once on a new connection, and is back within its bound within a second of the relay answering.

Avatars on the avatar channel

An avatar moves, animates and gestures all the time, so its state travels on a channel of its own rather than as transform deltas and Sync fields: one small datagram a frame (about 40 bytes), 20 a second while the avatar moves or changes and one a second while it stands, so a walking avatar with changing parameters costs under 1 KB/s. A frame carries the root (position, rotation, the velocity the engine measures, a gait and a grounded flag), the avatar's parameters packed into a block of at most 256 bits (a bool takes 1 bit, an int 0 to 255 and a float -1 to 1 take 8), up to six IK targets in the root's frame (head, leftHand, rightHand, hips, leftFoot, rightFoot) and the emotes just started, each an id and a start time on the session clock. Every peer opens the channel for the avatar with the same declaration, usually from the avatar's own component:

local PARAMETERS = {
  { name = "Smile",   type = "float" },
  { name = "Gesture", type = "int" },
  { name = "Seated",  type = "bool" },
}

function start()
  multiplayer.setAvatarChannel(self.entity, { parameters = PARAMETERS })  -- every peer
end

function update(dt)
  if self.entity:isLocal() then
    -- The owner states it; the root comes from the entity's own transform.
    multiplayer.setAvatarState(self.entity, {
      gait = speed > 3 and 2 or (speed > 0.1 and 1 or 0),
      grounded = onGround,
      parameters = { Smile = smile, Gesture = gesture },
      targets = { head = { position = headLocal, rotation = headRotation } },
    })
  else
    -- Every other peer reads it, drawn on the session clock.
    local a = multiplayer.avatarState(self.entity)
    if a then
      animate(a.gait, a.velocity, a.parameters)
      for _, emote in a.emotes do
        if emote.startedAt > lastEmote then
          lastEmote = emote.startedAt
          play(emote.id, multiplayer.sessionTime() - emote.startedAt)  -- in phase on every peer
        end
      end
    end
  end
end

multiplayer.avatarEmote(self.entity, WAVE)   -- the owner: every peer lists it with its start time

A receiving peer draws the root like any remote body (above: the same delay, extrapolation and teleport settings, multiplayer.smoothing(e) reading its stream), and reads the gait, velocity and IK targets at the moment it draws, interpolated between the frames either side of it. A frame that arrives late lands in its place; parameters are the newest block received, read only under the same declaration (avatarState(e).stream.layoutMismatches counts the blocks a different declaration packed). Parameter changes are coalesced to 10 blocks a second, and a changed block and an emote ride every frame for a moment after, so a lost datagram loses neither. setAvatarChannel(e, { rate, parameterRate, targetRate }) changes how often (rate 1 to 30 a second).

An avatar that declares its parameters as data (parameters, animator and menu in its avatar.json, the topics/avatars guide) gets all of this from its AvatarAnimator: it opens the channel with the avatar's synced parameters on every peer, states them from the owner and draws them everywhere else.

The relay takes an avatar's frames from its owner alone (a frame another peer sends for it is refused and counted in getDiagnostics().refusals), holds each avatar to 40 frames a second and each frame to the largest the channel builds, and forwards each peer what it needs: every frame while the avatar is within 10 m of an avatar that peer states (its own, or any other it owns), about 10 a second further away inside its view, and about 2 a second behind it, with a frame that carries a parameter block or an emote that peer does not hold yet going to it at once, wherever it stands. avatarState(e).traffic states the cost: frames and bytes a second sent (on the owner) or received (on each other peer).

Why isn't this arriving? — reading what the engine is replicating

When a synced value does not show up on the other client, ask the engine what it is doing with it rather than standing up a second peer and concluding from absence. multiplayer.observe() reports everything this engine is replicating, and the two calls under it answer the question at the granularity it is asked at:

-- Everything this entity syncs: its owner, the room it broadcasts into, and
-- every REGISTERED synced component with its declared property names. It is
-- nil when the session holds no replication record for the entity at all,
-- which is itself an answer — nothing about it reaches anyone.
local record = multiplayer.observeEntity(id)
if record then
    print(record.room, record.roomPeers .. " other peer(s) share it")
    for _, c in ipairs(record.components) do
        for _, p in ipairs(c.properties) do
            print(c.componentType, p.name, "index " .. p.index, p.visibility, p.dirty)
        end
    end
end

-- Why one property is not reaching them. This answers for any entity,
-- including one with no record.
local verdict = multiplayer.explain(id, "Health", "hp")
if not verdict.arriving then print(verdict.reason) end

reason is one name from a closed set, and each names the thing to fix:

reasonwhat it means
noSessionthis engine holds no relay session at all
notConnecteda session exists and the relay link is down
entityNotSyncedthe entity has no sync record, so none of it goes on the wire
componentNotRegisteredno synced component of that type is registered on it
propertyNotDeclaredthe component is registered and never declared that name
awaitingEntitytraffic for this entity is held here, waiting for its spawn
notOwneranother peer owns it, so writes made here are not sent
roomNotJoinedthis client is not in the room the entity broadcasts into
noPeersInRoomnobody else is in that room to receive it
pendingSendit changed and the next sync tick has not carried it yet

propertyNotDeclared is the one that ends most searches: a name absent from record's property list is a name the component's Sync declaration never registered, which is invisible from the component's source alone.

Every reason speaks for relay replication — the per-property deltas a synced component puts on the wire. Edit mode carries a second channel beside it, the one the top of this guide describes: writing to /zero/source is sharing it, and a scene-authored entity's changes travel with that source. Scene content is left out of the sync-id pass on purpose, so in edit mode observe().entities holds the runtime-synced entities and every property on a scene entity reads entityNotSynced — the surface reporting that this entity's channel to the other clients is the source, which the VFS write path carries. What the reasons above are about is the other channel: an entity from entity.spawnSynced, and a component added with component.addSynced or declaring Sync.

The rest of the document answers the questions around it. multiplayer.getRooms() lists the relay rooms this client joined and multiplayer.roomFor(id) the one an entity broadcasts into, so a room key is read rather than rebuilt. A room key is {worldGuid}/{profile}/{branch}/{mode}/{sceneGuid}: two clients on different branches of a world are in different rooms. multiplayer.roomKey() is the key of the root scene in the current mode and multiplayer.roomKeyFor(sceneGuid, mode) builds the key of any scene. A two-player test runs in one room: put the user's client and your own sub-client in play on the same scene and read state.rooms.<key>.sameContent in the engine state. Work in your own sub-client by default and use the user's client when the test needs it; man subclient has the rule. multiplayer.syncTotals() counts what the registry holds — entities, component instances, declared properties and functions, how many components hold a dirty property this tick, and addsWaiting, the components whose ComponentAdd has yet to go out (queued for the next frame, or waiting for their entity to be announced). multiplayer.heldMessages() enumerates what getDiagnostics().messagesAwaitingEntity counts, each with the entity it names and how long it has waited. Every property carries lastSentMs and lastReceivedMs on the same clock as sampledAtMs, so subtracting two of them gives the interval between a send and what came back. getDiagnostics().reliableInFlight counts the reliable messages this peer has sent that the relay has not yet taken; it reads near 0 while the link keeps up, and on the owner of a value that arrives late elsewhere a count that grows says the changes are still on their way out of this peer.

The same document is a file: /zero/runtime/sync/replication is the whole of it, /zero/runtime/sync/entities/<entityId> one entity's record, and /zero/runtime/sync/rooms the joined keys. It answers in edit mode as well as play mode, for what the relay carries in each. A read of one of these files answers the document as of the last frame, the way multiplayer.observe() does. When nothing has read the surface for a while, the read waits the frame it takes to assemble a current one: vfs.read from code that can yield, shell.runAsync, and a shell or tool read from outside the engine all wait for it. A reader on the engine's own frame that cannot yield (a script's synchronous shell.run) is answered not ready for that read, and a read on the next frame answers the current document. Listing /zero/runtime/sync/entities follows the same rule: vfs.list from code that can yield, and a shell or tool listing, wait the frame for a current listing, and a listing from code that cannot yield raises VFS_READ_CANNOT_WAIT. /zero/runtime/sync/session and /zero/runtime/sync/peers answer what multiplayer.isConnected(), getPeerId() and getPeers() answer at the moment of the read.

A component that arrived before its asset

A component a peer delivers can name an asset this engine does not hold yet: a file still syncing, or a visitor's carried content whose mount is still filling. The component arrives and waits instead of failing: its awake() runs, or a delivered write to it lands, the moment the asset resolves, with nothing sent again. asset.pending() lists what this engine is waiting on ({ count, entries }, each naming the entity, component, field and reference, with state pending or refused and why), so a check waits on that list emptying. Every peer holds and applies a delivered reference the same way.

Beyond this

The multiplayer namespace also exposes collaborative undo/redo, room/mode state, and diagnostics — lsp.methods("multiplayer") lists it. The concept to hold onto: the world is shared at all times; Sync/NoSync and entity ownership are how you decide what everyone sees.

Replication is for live state — what's happening right now. For state that must survive restarts and be there next session (progression, saves, per-player records), reach for runtime_data (the runtime-data guide) instead: it's the world's durable, shared memory, where replication is its short-term memory.

  • documentation
  • guide