🐾PurrNet Docs
Sync Type

SyncVar

SyncVar<T> is a networked variable that automatically replicates its value from the server (or owner) to all clients whenever it changes.

SyncVar<int> health= 100
health100/100
ServerClient A (Owner)100Client B100Client C100

How it works

Declare a SyncVar<T> as a field on your NetworkBehaviour. Whenever you assign to .value, PurrNet detects the change and queues a sync packet on the next tick (or after the send interval). All observers receive the update and their local .value is updated automatically. New clients joining mid-game receive the current value immediately.

SyncVar works with any type PurrNet can serialize: primitives, structs with IPackedAuto, Vector3, Quaternion, string, enums, and more.

Constructor Parameters

ParameterTypeDefaultDescription
defaultValueT—Initial value before any sync occurs. Applied on all clients before the first network update arrives.
ownerAuthboolfalseWhen true, the owner (not just the server) can write this SyncVar. Used for owner-driven state like local player settings.
sendIntervalInSecondsfloat0 (every tick)Minimum time between syncs. Setting > 0 batches changes and reduces bandwidth at the cost of update frequency.

Basic usage

PlayerStats.cs
using PurrNet;
using UnityEngine;

public class PlayerStats : NetworkBehaviour
{
    // Synced health — server writes, all clients read
    private SyncVar<int> _health = new(100);

    // Owner-auth name — only the owner can set their own name
    private SyncVar<string> _playerName = new("Player", ownerAuth: true);

    // Throttled score — sync at most every 0.5 seconds
    private SyncVar<int> _score = new(0, sendIntervalInSeconds: 0.5f);

    private void Awake()
    {
        _health.onChanged += OnHealthChanged;
        _playerName.onChanged += OnNameChanged;
    }

    private void OnHealthChanged(int newValue)
    {
        // Called on ALL clients when health changes
        healthBar.SetValue(newValue, _health.previousValue);
        if (newValue <= 0) Die();
    }

    private void OnNameChanged(string newName)
    {
        nameTag.text = newName;
    }

    // Only server should call this directly
    public void TakeDamage(int amount)
    {
        if (!isServer) return;
        _health.value = Mathf.Max(0, _health.value - amount);
    }
}

Declare in fields, not methods

SyncVar must be declared as a class field (or property) on a NetworkBehaviour. Creating one inside a method or adding it to a list will break synchronisation.

Reading the previous value

The onChanged callback receives only the new value. To access the previous value, use syncVar.previousValue inside the callback.

Situational examples

Sync ammo with UI feedback

WeaponController.cs
public class WeaponController : NetworkBehaviour
{
    [SerializeField] private int maxAmmo = 30;
    private SyncVar<int> _ammo = new(30);
    private SyncVar<bool> _isReloading = new(false);

    private void Awake()
    {
        _ammo.onChanged += (newAmmo) =>
        {
            ammoDisplay.text = $"{newAmmo}/{maxAmmo}";
            if (newAmmo == 0 && !_isReloading.value)
                StartReload();
        };
        _isReloading.onChanged += (reloading) =>
            reloadIndicator.SetActive(reloading);
    }

    [ServerRpc(requireOwnership: true)]
    public void CmdFire()
    {
        if (_ammo.value <= 0 || _isReloading.value) return;
        _ammo.value--;
        // Fire logic...
    }

    [ServerRpc(requireOwnership: true)]
    public void CmdReload()
    {
        if (_isReloading.value || _ammo.value == maxAmmo) return;
        _isReloading.value = true;
        StartCoroutine(ReloadCoroutine());
    }

    private IEnumerator ReloadCoroutine()
    {
        yield return new WaitForSeconds(2f);
        _ammo.value = maxAmmo;
        _isReloading.value = false;
    }
}

Syncing a custom struct

Register a custom type with [RegisterNetworkType] and implement IPackedAuto for automatic field serialization.

PlayerData.cs
[RegisterNetworkType(typeof(PlayerData))]
public struct PlayerData : IPackedAuto
{
    public int level;
    public int experience;
    public string displayName;
}

public class PlayerProfile : NetworkBehaviour
{
    private SyncVar<PlayerData> _data = new(new PlayerData { level = 1, displayName = "New Player" });

    private void Awake()
    {
        _data.onChanged += (data) => UpdateProfileUI(data);
    }
}

Avoid syncing every frame

Do not set .value in Update()without checking for an actual change. PurrNet batches changes per tick, but creating dirty flags every frame wastes CPU even when the value hasn't changed. Always guard: if (_speed.value != newSpeed) _speed.value = newSpeed;

ownerAuth and server writes

When ownerAuth: true, only the owner can write from the client side. The server can always write regardless. If you need to override an owner-protected var from the server, call from server-side code (inside an if (isServer) guard).