Unity Client
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.
| Component | Where to put it | Role |
|---|---|---|
NetworkWorld | One per scene | Creates, updates, and destroys GameObjects from the received state, and sends changes in batches |
NetworkEntity | The root of each synced Prefab | Associates a GameObject with a shared object. Handles reading and writing values, reflecting them in the display, and control |
NetworkTransform | Prefabs that sync position and rotation | Sends 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).
| Member | Description |
|---|---|
Connect(accessToken, ipAddress, port, encryptionKey) | Connect to the room |
Disconnect() | Disconnect. Disconnected is raised when done |
State | Disconnected, Connecting, Synchronizing (applying the snapshot), or Ready |
Attached | Raised right after the NetworkWorld is attached. Register world.Client events here |
Ready | Raised when the snapshot is applied and you can spawn and send |
Disconnected | Raised 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.
- Connect with
RealtimeSessionand getMyConnectionId(your connection ID). - Call
world.Attach(connectionId, send).sendis a function that receives the data to send and pushes it onto the send queue. - Pass the data received in
session.OnMessageWithMetadatatoworld.Receive(payload, metadata.LifeTimeMilliSeconds). Register it before startingsession.Dispatch()so you don’t miss the snapshot sent right after joining. - 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.
- Create a Prefab for display and add NetworkEntity to its root. If you also sync position and rotation, add NetworkTransform as well.
- In the Project window, create a catalog with Create > GS2 > Realtime > Prefab Catalog.
- In the catalog’s Prefabs, register the Prefab ID (Id) and the Prefab for display.
- 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.
| Item | Description |
|---|---|
| Position Axes / Rotation Axes | The axes to sync. Selecting an axis the server does not allow causes an error. If only position is allowed, set Rotation Axes to None |
| Target | The Transform to move. If empty, its own Transform |
| Interpolation | The interpolation speed when you are not passing the server time. If 0, it moves to the received value immediately |
| Teleport Distance | Moves without interpolation to positions farther than this distance (for respawns, etc.). If 0, it always interpolates |
| Interpolation Delay | When 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.
- Put the generated
.realtimeschemaunderAssets. It is imported as a sync schema asset. - Specify that asset in the Prefab’s NetworkEntity > Schema.
- Add an entry with NetworkEntity > Property bindings > Add binding, and select the value with Field.
- 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.
| Method | Description |
|---|---|
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.
| Member | Description |
|---|---|
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 Enable | Automatically requests control when enabled |
| Auto Renew | Automatically renews control before it expires (enabled by default) |
| Controlled Behaviours | Scripts 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 Changed | Whether you can operate it now / the event fired when that changes |
LastResult / Command Completed | The 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).IsSpawnedbecomestrueonce confirmed.entity.SpawnRequestgives the room’s answer (see the table below). Synchronized values (SetIntand so on) are available after confirmation; set initial values inworld.Spawnedor 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.SpawnFailedis called and the instance is destroyed. - To wait for spawn confirmation before creating the GameObject, use
world.Spawn(prefabId, position, rotation). The returnedSpawnRequestcompletes once, when the result is known. Wait for it withyield return request, or receive it withrequest.OnCompleted(r => ...).
SpawnRequest.Status | Description |
|---|---|
Pending | Waiting for the room’s response |
Spawned | Spawned. Entity is the confirmed instance |
Rejected | The room refused it. The reason is in Rejection (such as the ownership limit) |
NotSent | Could not be sent (256 packets are already waiting to be sent) |
Abandoned | No answer will come (disconnected, or rejoined the room on reconnection) |
| Member | Description |
|---|---|
IsMine | Whether you can modify it (the owner of a player object, or the holder of lease control) |
OwnerId | The 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" |
OwnershipChanged | The 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 onlyTargets 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 inpublicMethods([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 returnsIEnumerator, 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
nulldeletes the property. WithSyncClientdirectly, the room’s scope isSyncClient.RoomScope,DeleteProperty(scope, key)deletes a property, andSetTextProperty/TryGetTextPropertywrite 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.
| Member | Description |
|---|---|
world.MasterClientId / IsMasterClient | The master’s connection ID / whether you are the master |
world.SetMasterClient(connectionId) | Changes the master. Only the master can call it |
world.MasterClientChanged | The 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 generatedunity/<EnumName>.csand set inputs by the same names, as inworld.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)orSetInput(slot, float, precision). To set them per tick, use theInputSamplingevent. - 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 fromInputTick. IsMineistruefor the owner, but it can neither write values norDestroythem.- 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,
NetworkTransformcloses the gap over aboutCorrectionTime(0.1 seconds by default). NetworkObject.Valueskeeps the values received from the room. Read predicted values fromPredictedValues. Objects withIsPredictedset totrueare predicted.- Predicted spawns are announced by
NetworkWorld.PredictedSpawned. When the room’s object arrives, the same instance gets itsNetworkEntity.Object. Objects despawned by the prediction stop rendering until the room despawns them (NetworkObject.PredictedRemoved). - For lag compensation, keep
NetworkWorld.ViewDelayequal toNetworkTransform.InterpolationDelay(0.1 seconds by default).ViewDelaycan also be set in the Inspector. For an accurate value, pass the server time withworld.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;Pollregisters with the room and keeps the registration alive. When the room responds,Activebecomestrue; after 10 seconds without a response, it returns tofalse. While it isfalse, 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.
| Symptom | What to check |
|---|---|
You get an Unknown prefab ID error | Whether the Prefab ID in the server rules matches the catalog’s Id |
Select a field from the schema is displayed | Whether 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 only | Whether NetworkTransform’s Rotation Axes is None |
| Nothing is sent when you move | Whether you have acquired control. Whether the movement script is registered in Controlled Behaviours |
| Operations are refused | Check world.CommandRejected (also logged as a warning) for the refused command, the target ID and the reason |
| Values don’t change with Inspector events | Whether you selected a Dynamic event instead of one that passes a fixed value |
Objects created with world.Instantiate disappear | Check the result in SpawnFailed |
UDP does not become Active | Whether 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.