Unity Client

Components and settings for displaying and operating shared objects in Unity

In sync and stateMachine rooms, the objects in the room are displayed as Unity GameObjects. This page explains the Unity-side settings and APIs, organized by what you want to do. How syncing works (who can modify what, send order, reconnection and so on) is the same for every engine, so it is collected in How Object Sync Works.

If you use Godot, see the Godot Client.

If you are migrating from Photon (PUN2), the Migration Guide from Photon has a mapping table.

If this is your first time, working through the tutorials (Object Sync, Server-Side Logic, Rollback Sync) first makes the role of each setting easier to grasp. For how to write server-side rules, see the Room Definition Reference.

Overview

For the terms and the flow of data, see How Object Sync Works.

In Unity, you use the following three components. The namespace is Gs2.Realtime.Sync.

ComponentWhere to put itRole
NetworkWorldOne per sceneCreates, updates, and destroys GameObjects from the received state, and sends changes in batches
NetworkEntityThe root of each synced PrefabAssociates a GameObject with a shared object. Handles reading and writing values, reflecting them in the display, and control
NetworkTransformPrefabs that sync position and rotationSends the movement of objects you can operate, and interpolates to the received position on other clients

To send operations to objects that the server updates, also add SharedObject.

Connect to a Room

Add NetworkSession to the same GameObject as the NetworkWorld, and call Connect with the room’s connection information and an access token. For concrete code, see the connection script in the tutorial.

var session = GetComponent<NetworkSession>();
// Subscribe once (e.g. in Awake); subscribing per connection repeats them on reconnect
session.Ready += () => world.Instantiate(prefabId, position, rotation); // after the snapshot is applied
session.Disconnected += reason => ShowTitle(reason);                    // the world is already detached
// On each connection or reconnection
session.Connect(accessToken, ipAddress, port, encryptionKey);

NetworkSession connects with RealtimeSession, attaches the NetworkWorld, and handles the send queue, receiving with the server time, UDP (except on WebGL), and cleanup on disconnect.

RPCs, spawns, events, properties and other commands may be called at any time after connecting (Send Order).

MemberDescription
Connect(accessToken, ipAddress, port, encryptionKey)Connect to the room
Disconnect()Disconnect. Disconnected is raised when done
StateDisconnected, Connecting, Synchronizing (applying the snapshot), or Ready
AttachedRaised right after the NetworkWorld is attached. Register world.Client events here
ReadyRaised when the snapshot is applied and you can spawn and send
DisconnectedRaised on disconnect, with a reason string. Includes disconnects by the other side, connection failures, and send or decode failures

Writing Your Own Connection Handling

You can also wire up your own transport without NetworkSession. NetworkWorld does not connect or log in, so pass it in the following order.

  1. Connect with RealtimeSession and get MyConnectionId (your connection ID).
  2. Call world.Attach(connectionId, send). send is a function that receives the data to send and pushes it onto the send queue.
  3. Pass the data received in session.OnMessageWithMetadata to world.Receive(payload, metadata.LifeTimeMilliSeconds). Register it before starting session.Dispatch() so you don’t miss the snapshot sent right after joining.
  4. When disconnected, call world.Detach(). All displayed GameObjects are destroyed.

LifeTimeMilliSeconds is the room server’s clock. When you pass it, you can use world.ServerTime (seconds), a time shared by all participants in the room, and other players’ objects move smoothly according to the time they were received. world.Receive(payload) alone also works.

For how to send state over UDP, see Send State over UDP.

send receives a data array and its valid length, and returns true if it could push the data onto the send queue (false otherwise: the client keeps that packet, in order, and offers it again later). The array is reused, so copy the valid range before queuing it. If sending fails, do not discard the changes; disconnect, reconnect, and rebuild the display from the snapshot.

RelayRealtimeSession wraps messages in a different format, so it cannot be used for this purpose.

Register Prefabs

Register the Prefabs that display objects received from the server, one per Prefab ID.

  1. Create a Prefab for display and add NetworkEntity to its root. If you also sync position and rotation, add NetworkTransform as well.
  2. In the Project window, create a catalog with Create > GS2 > Realtime > Prefab Catalog.
  3. In the catalog’s Prefabs, register the Prefab ID (Id) and the Prefab for display.
  4. Specify the catalog in NetworkWorld > Prefab Catalog in the scene.

Register every Prefab ID the server might send. An error occurs if an unregistered ID arrives. The Prefab root needs a NetworkEntity.

Shared objects are created by the room. When a player creates their own object, use world.Instantiate instead of Unity’s Instantiate. GameObjects created with Unity’s Instantiate are not shared with other participants.

If you want the room to check spawns and RPCs, set an object catalog.

Sync Position and Rotation

The SDK has standard fields for position and rotation, so you can sync them without a sync schema asset. In NetworkTransform, select only the axes the server allows to sync (Position and Rotation).

The NetworkTransform settings are as follows.

ItemDescription
Position Axes / Rotation AxesThe axes to sync. Selecting an axis the server does not allow causes an error. If only position is allowed, set Rotation Axes to None
TargetThe Transform to move. If empty, its own Transform
InterpolationThe interpolation speed when you are not passing the server time. If 0, it moves to the received value immediately
Teleport DistanceMoves without interpolation to positions farther than this distance (for respawns, etc.). If 0, it always interpolates
Interpolation DelayWhen passing the server time, how many seconds in the past the displayed pose is (default 0.1). Interpolates between the updates received before and after

When all three rotation axes are synced, rotation is interpolated as a Quaternion. Axes you don’t select keep each client’s local value.

For objects you can operate, move the Transform as usual in your movement script, and NetworkTransform rounds the values to the step size and sends them. Jitter smaller than the step size is not sent.

Display Custom Values

For custom values such as HP or an open/closed state, declare them as RoomSchema on the server side and use the generated sync schema (.realtimeschema) in Unity. For how to write the declaration, see Sync Schema.

  1. Put the generated .realtimeschema under Assets. It is imported as a sync schema asset.
  2. Specify that asset in the Prefab’s NetworkEntity > Schema.
  3. Add an entry with NetworkEntity > Property bindings > Add binding, and select the value with Field.
  4. Register the target in Apply to, and select a Dynamic event that takes the received value as its argument.

The event argument type corresponds to the sync schema type (int / bool / float). For example, you can connect a bool to a GameObject’s SetActive(bool), or a float to a Slider’s value. The event is called right after joining and every time the value changes.

From scripts, you can read and write values with the following NetworkEntity methods.

MethodDescription
GetInt / GetBool / GetFloat(name)Read a value. If you can write the object, this is the value you last Set for that field (even before it is sent). Otherwise, the value received from the room
GetConfirmedInt / GetConfirmedBool / GetConfirmedFloat(name)Read the value received from the room. Does not include your own writes
SetInt / SetBool / SetFloat(name, value)Send a value. Requires write permission for that object

To write sending and receiving together in a script, put a component that implements INetworkObservable on the Prefab. It corresponds to Photon’s OnPhotonSerializeView.

public sealed class Health : MonoBehaviour, INetworkObservable
{
    public float Value;
    // Called on the owner, just before changes are sent in a batch
    public void OnNetworkWrite(NetworkEntity entity) => entity.SetFloat("Health", Value);
    // Called on other clients when a value arrives
    public void OnNetworkRead(NetworkEntity entity, uint changed)
    {
        if (entity.HasChanged("Health", changed))
            Value = entity.GetFloat("Health");
    }
}

Property bindings only pass received values to the display. Moving the Slider locally does not change the server’s value (Custom Values). Change server-managed values by sending operations to the server.

Send Values with Control

For objects the server declares as “lending control”, only the player who has obtained control (lease) can send values. For the rules of control (reasons for refusal, expiry, what happens when the holder changes), see Control.

MemberDescription
RequestControl() / ReleaseControl()Request to acquire / release control. Can also be registered to a Button’s On Click
AcquireControl()Makes the same request as RequestControl() and returns a ControlRequest you can wait on until you have control (below)
Acquire On EnableAutomatically requests control when enabled
Auto RenewAutomatically renews control before it expires (enabled by default)
Controlled BehavioursScripts enabled only while you can operate the object (movement and input handling): while you have control of a shared object, or while you own a player object or simulated object. Do not register networking components
HasControl / Control ChangedWhether you can operate it now / the event fired when that changes
LastResult / Command CompletedThe result of an acquire or release request

A rejected request is not retried automatically, so call RequestControl() again if needed.

To start operating once the acquisition succeeds, use AcquireControl().

var request = entity.AcquireControl();
yield return request; // or: request.OnCompleted(r => ...)
if (request.Status == RequestStatus.Succeeded) { /* HasControl is true and Controlled Behaviours are enabled */ }

Status is one of Succeeded, Refused (the reason is in Result) or Abandoned (ReleaseControl(), the GameObject disabled, the object removed).

SharedObject.Acquire(), Renew() and Release() manage the lease manually. They only return the room’s answer; they neither enable Controlled Behaviours nor renew automatically. Normally use AcquireControl() or RequestControl().

When the GameObject is disabled, control is released automatically.

Send Operations to the Server

Clients cannot rewrite the values of server-managed objects (such as an enemy’s HP). Instead, send an operation request with SharedObject.Interact(method) (Send Operations to the Server).

var target = GetComponent<SharedObject>();
var request = target.Interact(DoorAction.Open); // the rules' [RoomAction] enum (unity/DoorAction.cs)
request.OnCompleted(r => Debug.Log(r.Status + " " + r.Result)); // or: yield return request;

You can pass the enum generated from the rules’ [RoomAction] enum as is (passing the number, as in Interact(1), also works). You cannot send additional arguments.

Interact (and the lease’s Acquire, Renew and Release) returns a CommandRequest that completes once. Status (RequestStatus) is one of Succeeded, Refused (the reason is in Result), NotSent or Abandoned. For their meanings and the list of result codes, see Send Operations to the Server. Every request’s result also arrives through NetworkWorld.Client.CommandCompleted (object ID, request ID, result).

When you use SyncClient directly, pass a callback to Spawn, Lease or Interact to receive the result once, with the same RequestStatus.

client.Interact(objectId, (uint)DoorAction.Open, (status, result) => Debug.Log(status + " " + result));

Reset and the snapshot after a reconnection complete the waiting requests with Abandoned. AbandonRequests() ends them explicitly.

Create Player Objects

Create objects owned by a player, such as the character the player controls, with world.Instantiate. It corresponds to Photon’s PhotonNetwork.Instantiate.

var entity = world.Instantiate(prefabId, position, rotation);
entity.Rpc(nameof(Weapon.Equip), RpcTarget.AllBuffered, 3); // Usable right after creation
  • You can use the returned NetworkEntity immediately as your own (IsMine) (Player Objects). IsSpawned becomes true once confirmed. entity.SpawnRequest gives the room’s answer (see the table below). Synchronized values (SetInt and so on) are available after confirmation; set initial values in world.Spawned or similar. Using them before confirmation fails with an error that says so.
  • Position and rotation are set on the axes synced by the Prefab’s NetworkTransform.
  • If the room rejects the spawn (the ownership limit is exceeded, or the Prefab is not registered in a room that has an object catalog), world.SpawnFailed is called and the instance is destroyed.
  • To wait for spawn confirmation before creating the GameObject, use world.Spawn(prefabId, position, rotation). The returned SpawnRequest completes once, when the result is known. Wait for it with yield return request, or receive it with request.OnCompleted(r => ...).
SpawnRequest.StatusDescription
PendingWaiting for the room’s response
SpawnedSpawned. Entity is the confirmed instance
RejectedThe room refused it. The reason is in Rejection (such as the ownership limit)
NotSentCould not be sent (256 packets are already waiting to be sent)
AbandonedNo answer will come (disconnected, or rejoined the room on reconnection)
MemberDescription
IsMineWhether you can modify it (the owner of a player object, or the holder of lease control)
OwnerIdThe owner’s connection ID. For shared objects, the holder of control (0 if none)
Destroy()Destroys your own player object
TransferOwnership(connectionId)Transfers ownership to another participant (Photon’s TransferOwnership). Player objects only
RequestOwnership()Takes ownership (Photon’s RequestOwnership). In a room with an object catalog, only for objects with "ownership": "takeover"
OwnershipChangedThe event fired when the owner changes

For what happens when the owner leaves, and the rules of ownership periods, see Player Objects.

RPC

Add [NetworkRpc] to a method of a Prefab component to make it callable from other clients. It corresponds to Photon’s [PunRPC] and photonView.RPC.

public sealed class Weapon : MonoBehaviour
{
    [NetworkRpc] // public, so that other classes can name it with nameof(Weapon.Fire)
    public void Fire(Vector3 direction, int damage, NetworkRpcInfo info)
    {
        // info.Sender is the connection ID of the calling player (set by the server)
    }
}

entity.Rpc(nameof(Weapon.Fire), RpcTarget.Others, direction, 10);
entity.RpcTo(nameof(Weapon.Fire), connectionId, direction, 10); // Send to one player only

Targets are RpcTarget.All, Others, Owner, AllBuffered and OthersBuffered, plus RpcTo for one player. For their meanings, see RPC.

  • The RPC ID is determined from the method name (you can also fix it with [NetworkRpc(id)]). The NetworkEntity Inspector shows the IDs of the RPCs on the Prefab.
  • To restrict who may call which RPC, set an object catalog. With one, only the owner may call the IDs in methods, and RPCs called on other players’ objects go in publicMethods ([NetworkRpc(AnyCaller = true)] puts them there when the catalog is generated).
  • Supported argument types are bool, integer types, char, float, double, string, byte[], enum, Vector2/3/4, Vector2Int/3Int, Quaternion, and Color. If the last argument is NetworkRpcInfo, you receive the caller. If the method returns IEnumerator, it runs as a coroutine.

Room Events

Send notifications not tied to an object with room events. They correspond to Photon’s RaiseEvent and OnEvent.

public sealed class Scoreboard : MonoBehaviour
{
    void OnEnable() => world.AddEventTarget(this);
    void OnDisable() => world.RemoveEventTarget(this);

    [NetworkEvent]
    void Goal(int team, NetworkRpcInfo info) { /* ... */ }
}

world.RaiseEvent("Goal", RpcTarget.All, 1);
world.RaiseEventTo("Goal", connectionId, 1);

For targets and how Buffered events are handled, see Room Events. Arguments are encoded according to the declaration of the registered handler method. To handle raw bytes without a handler, use RaiseRawEvent (RaiseRawEventTo for one player) and EventReceived. With SyncClient directly, the receivers are an RpcTarget too (Rpc, RaiseEvent), and one player is reached with RpcTo and RaiseEventTo, so a target and a recipient cannot be mixed up.

Custom Properties

Values attached to the room or to players. They also reach players who join later. They correspond to Photon’s room and player custom properties.

world.SetRoomProperty("stage", "forest");
world.SetPlayerProperty("team", 2);   // You can write only your own properties
world.RoomPropertyChanged += key => { /* ... */ };
if (world.TryGetPlayerProperty<int>(connectionId, "team", out var team)) { /* ... */ }
  • Supported value types are the same as RPC arguments (enums are stored as integers). Writing null deletes the property. With SyncClient directly, the room’s scope is SyncClient.RoomScope, DeleteProperty(scope, key) deletes a property, and SetTextProperty / TryGetTextProperty write and read UTF-8 text.
  • For when writes take effect and the limits, see Custom Properties.

Master Client

For how the master is chosen, see Master Client.

MemberDescription
world.MasterClientId / IsMasterClientThe master’s connection ID / whether you are the master
world.SetMasterClient(connectionId)Changes the master. Only the master can call it
world.MasterClientChangedThe event fired when the master changes

Interest Group

Divide objects into groups and deliver updates only to players subscribed to them. It corresponds to Photon’s PhotonView.Group and SetInterestGroups.

entity.SetGroup(5);          // The owner sets the object's group (0 reaches everyone)
world.SubscribeGroup(5);     // Receive updates for group 5
world.UnsubscribeGroup(5);

For what groups filter and the limits, see Interest Group.

Control Objects Moved by Ticks

When the room rules use DefineTickRate and DefineSimulatedPrefab, the server moves objects of that kind from inputs (ticks). The client sends inputs instead of writing positions (Ticks and Prediction).

// Spawn your character (a simulated prefab)
var me = world.Instantiate(5, Vector3.zero, Quaternion.identity);

// Set the current input every frame
void Update()
{
    world.SetInput(0, Mathf.RoundToInt(Input.GetAxisRaw("Horizontal")));
    world.SetInput(1, Mathf.RoundToInt(Input.GetAxisRaw("Vertical")));
    world.SetInput(2, Input.GetButton("Fire1"));
    // Aim direction for Room.Raycast (x 1000)
    world.SetInput(3, Mathf.RoundToInt(aim.x * 1000));
    world.SetInput(4, Mathf.RoundToInt(aim.y * 1000));
}
  • When the rules name the slots with a [RoomInput] enum, copy the generated unity/<EnumName>.cs and set inputs by the same names, as in world.SetInput(MoveInput.X, 1). Slots are typed, so passing a sync schema field instead is a compile error.
  • Set inputs with SetInput(slot, int), SetInput(slot, bool) or SetInput(slot, float, precision). To set them per tick, use the InputSampling event.
  • A working sample is in the SDK at Assets/Scenes/Samples/Realtime/Arena (predicted movement, lag-compensated shots and predicted rocket spawns).
  • How many ticks ahead inputs are stamped is InputLeadTicks (2 ticks by default), and the stamped tick number can be read from InputTick.
  • IsMine is true for the owner, but it can neither write values nor Destroy them.
  • You can register the scripts that send inputs in Controlled Behaviours. They are enabled only on simulated objects you own.

Predict Your Own Character

When the rules have code marked with [Predict] (prediction), the compiler emits <RuleClass>Prediction.cs. Add it to your Unity project and register it.

TickRoomPrediction.Register(world);  // for a rule class named TickRoom; before or after Attach
  • For how prediction behaves, see Ticks and Prediction. When a prediction was off, NetworkTransform closes the gap over about CorrectionTime (0.1 seconds by default).
  • NetworkObject.Values keeps the values received from the room. Read predicted values from PredictedValues. Objects with IsPredicted set to true are predicted.
  • Predicted spawns are announced by NetworkWorld.PredictedSpawned. When the room’s object arrives, the same instance gets its NetworkEntity.Object. Objects despawned by the prediction stop rendering until the room despawns them (NetworkObject.PredictedRemoved).
  • For lag compensation, keep NetworkWorld.ViewDelay equal to NetworkTransform.InterpolationDelay (0.1 seconds by default). ViewDelay can also be set in the Inspector. For an accurate value, pass the server time with world.Receive(bytes, milliseconds) (connect to a room).

Send State over UDP

Periodic updates such as positions are sent over UDP. It corresponds to Photon’s unreliable sending. For how UDP behaves (falling back to WebSocket, resending, ordering), see UDP.

NetworkSession uses UDP automatically (you can turn it off with Use Udp). When you write your own connection handling, do the following.

var udp = new RealtimeUdpChannel(session);  // Create after connecting
// Every frame
udp.Poll((bytes, milliseconds) => world.Receive(bytes, milliseconds));
world.Unreliable = udp.Active ? udp.TrySend : (TrySend)null;
  • Poll registers with the room and keeps the registration alive. When the room responds, Active becomes true; after 10 seconds without a response, it returns to false. While it is false, data is sent over WebSocket.
  • UDP is not available on WebGL. It works over WebSocket only.

Object Catalog

This setting makes the room check player object types, fields, RPCs and ownership requests. For the JSON format and items, see Object Catalog.

The IDs in methods can be fixed, as in [NetworkRpc(1)], or derived from names. You can check IDs derived from names in the NetworkEntity Inspector. RPCs with [NetworkRpc(AnyCaller = true)] go in publicMethods.

You can generate this JSON with Copy Object Catalog JSON in the catalog asset’s right-click menu. Prefabs the rules define (shared objects and simulated objects) are not included.

Object Lifetime, Room Termination and Send Volume

For how objects are handled on disconnect and reconnect, the relation to room termination conditions, and the estimated send volume, see Object Lifetime and Reconnection, Relation to Room Termination Conditions and Estimated Send Volume. NetworkWorld’s send interval is Send Rate (default 20 times per second; you can also change it with world.SendRate).

Troubleshooting

For checks common to every engine, see How Object Sync Works. Unity-specific checks are as follows.

SymptomWhat to check
You get an Unknown prefab ID errorWhether the Prefab ID in the server rules matches the catalog’s Id
Select a field from the schema is displayedWhether you specified the generated sync schema in Schema for the Prefab that uses custom values
You get a field error even though you sync position onlyWhether NetworkTransform’s Rotation Axes is None
Nothing is sent when you moveWhether you have acquired control. Whether the movement script is registered in Controlled Behaviours
Operations are refusedCheck world.CommandRejected (also logged as a warning) for the refused command, the target ID and the reason
Values don’t change with Inspector eventsWhether you selected a Dynamic event instead of one that passes a fixed value
Objects created with world.Instantiate disappearCheck the result in SpawnFailed
UDP does not become ActiveWhether the room’s port is open for UDP. UDP is not available on WebGL

Distribute the rules (GSL) and the sync schema as a pair generated together from the same C# definition.