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

Managing Network Variable States

Store and share dynamic game data using NetworkVariables to ensure all clients maintain a consistent state for properties like health or scores.

In this lesson, you will learn how to leverage NetworkVariable<T> to maintain a single, synchronized source of truth for dynamic game data across all connected clients.

Understanding Network Variables

In a multiplayer environment, local variables (like private int health) only exist in the memory of the client or server that modified them. If you want a player’s score or health to be consistent for everyone, you must use NetworkVariable<T>.

A NetworkVariable is a special container that tracks changes. When the server updates the value, the underlying networking engine automatically serializes that change and broadcasts it to all connected clients. This ensures that every player sees the exact same state for that property, regardless of network latency.

Implementation Pattern

To use these, your script must inherit from NetworkBehaviour and the variable must be defined as a member field. Here is how you might track a player’s health:

using Unity.Netcode;

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

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

Managing Permissions

Crucially, NetworkVariable includes read and write permissions. By default, only the server can write to these variables. This is vital for security; if you allow clients to modify their own Health variable directly, you invite cheating.

When you need to change a value (e.g., subtracting health when a player takes damage), perform the logic on the server via an Rpc or inside a server-side method, and let the NetworkVariable handle the synchronization back to the clients. The OnValueChanged callback then acts as the perfect hook to trigger local effects, like updating a health bar or playing a "take damage" animation.

Key Takeaway: NetworkVariable creates a synchronized state broadcasted from the server, ensuring all clients remain in lockstep with the game's authoritative data.