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. ReadPermissioncontrols who can see it (usuallyEveryone),WritePermissioncontrols who can change it (almost alwaysServer, to prevent cheating).OnValueChangedfires 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
NetworkVariableeach interval.