State synchronization keeps game data the same for all players in a multiplayer game. It helps everyone see the same game world at the same time.
State synchronization in Unity
using Unity.Netcode; public class PlayerState : NetworkBehaviour { public NetworkVariable<Vector3> Position = new NetworkVariable<Vector3>(); void Update() { if (IsOwner) { Position.Value = transform.position; } else { transform.position = Position.Value; } } }
NetworkVariable is used to share data automatically between server and clients.
IsOwner checks if this player controls the object to send updates only from the owner.
public NetworkVariable<int> Health = new NetworkVariable<int>(100);
if (IsServer) { Score.Value += 10; }
transform.position = Position.Value;
This script syncs the position of a game object across the network. The owner sends its position, and others update to match.
using Unity.Netcode; using UnityEngine; public class SimpleSync : NetworkBehaviour { public NetworkVariable<Vector3> syncedPosition = new NetworkVariable<Vector3>(); void Update() { if (IsOwner) { syncedPosition.Value = transform.position; } else { transform.position = syncedPosition.Value; } } }
Always update NetworkVariables only from the owner or server to avoid conflicts.
NetworkVariables automatically send updates, so you don't need to write extra code for syncing.
Test multiplayer syncing using Unity's Play Mode with multiple clients to see synchronization in action.
State synchronization shares game data between players to keep the game world consistent.
Use NetworkVariables to automatically sync data like position or health.
Only the owner or server should update the shared state to avoid errors.