0
0
Unityframework~5 mins

State synchronization in Unity

Choose your learning style9 modes available
Introduction

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.

When you want all players to see the same player positions in a multiplayer game.
When you need to share health or score updates between players.
When objects in the game world must move or change the same way for everyone.
When you want to keep game events like shooting or item pickups consistent across players.
Syntax
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.

Examples
This shares the player's health starting at 100 with all players.
Unity
public NetworkVariable<int> Health = new NetworkVariable<int>(100);
Only the server changes the score to keep it consistent.
Unity
if (IsServer)
{
    Score.Value += 10;
}
Clients update their object position to match the synchronized value.
Unity
transform.position = Position.Value;
Sample Program

This script syncs the position of a game object across the network. The owner sends its position, and others update to match.

Unity
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;
        }
    }
}
OutputSuccess
Important Notes

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.

Summary

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.