C# for Unity: Coroutines & Multiplayer Networking

Lesson 6 of 7

NetworkVariables and State Synchronization

RPCs are one-shot events. For continuous state, like health, score, or position, that every client should always see the current value of, use a NetworkVariable<T>.

public class PlayerHealth : NetworkBehaviour
{
    public NetworkVariable<int> Health = new NetworkVariable<int>(
        100,
        NetworkVariableReadPermission.Everyone,
        NetworkVariableWritePermission.Server
    );

    void Start()
    {
        Health.OnValueChanged += (oldValue, newValue) =>
        {
            Debug.Log($"Health changed: {oldValue} -> {newValue}");
        };
    }

    [ServerRpc]
    public void TakeDamageServerRpc(int amount)
    {
        Health.Value -= amount; // only the server may write
    }
}

The pieces

  • A NetworkVariable<T> automatically syncs its value from the server to every client, no manual RPC needed.
  • ReadPermission controls who can see it (usually Everyone), WritePermission controls who can change it (almost always Server, to prevent cheating).
  • OnValueChanged fires on every machine, server and clients, whenever the value updates, a good place to refresh UI or trigger effects.
  • Combine with coroutines when you need timed, server-authoritative changes, e.g. a coroutine on the server that ticks damage-over-time and writes to a NetworkVariable each interval.

📝 NetworkVariables Quiz

Passing score: 70%
  1. 1.Why should WritePermission on a NetworkVariable almost always be Server?

  2. 2.The ____ event on a NetworkVariable fires on every machine when its value changes.

  3. 3.A NetworkVariable requires you to write a ClientRpc every time its value changes in order to sync it.