Course contentsShow
← Unity Game Development
Lesson 792 of 82812. Multiplayer and DeploymentFree lesson

Implementing NetworkVariable for Continuous State Updates

Learners will synchronize simple game values like player health or scores across all connected clients using the NetworkVariable synchronization system.

Implementing NetworkVariable for Continuous State Updates

In this lesson, you will learn how to leverage NetworkVariable to automatically synchronize persistent data like player health or current scores across all connected clients without manually sending RPCs.

The Mechanism of Continuous State

When developing multiplayer games, you often have values that change frequently, such as a player’s current health during combat or a countdown timer. Instead of writing complex logic to broadcast these updates every time they change, NetworkVariable acts as a managed container that synchronizes its state automatically whenever a value is updated on the server.

Because NetworkVariable is part of the NetworkBehaviour class, the server maintains the "source of truth." When the server modifies a NetworkVariable, the underlying Netcode for GameObjects system automatically pushes that change to all connected clients. Clients then automatically update their local copies to match the server.

Implementation Example

To implement this, you declare a NetworkVariable inside your NetworkBehaviour script. You must specify the data type (which must be a "blittable" type or a supported struct) and define its NetworkVariableReadPermission.

using Unity.Netcode;

public class PlayerStats : NetworkBehaviour
{
    // Initialize the NetworkVariable with default values
    public NetworkVariable<int> Health = new NetworkVariable<int>(100);

    public override void OnNetworkSpawn()
    {
        // Subscribe to changes to update UI automatically
        Health.OnValueChanged += (oldValue, newValue) => {
            Debug.Log($"Health changed from {oldValue} to {newValue}");
        };
    }

    public void TakeDamage(int amount)
    {
        if (IsServer)
        {
            Health.Value -= amount;
        }
    }
}

By using the OnValueChanged delegate, you can hook your UI logic directly into the state change. This ensures that whenever the health changes on the server, every client’s UI updates immediately. Remember, only the server should modify the Value property of a NetworkVariable, as these values are intended to be authoritative. If a client attempts to change the value, it will be ignored or corrected by the server’s state.

Key Takeaway: Use NetworkVariable to maintain a single source of truth for game state, allowing the engine to handle the heavy lifting of delta-compression and automatic replication across the network.