SyncDictionary
SyncDictionary<TKey, TValue> is a networked dictionary that syncs add, update, and remove operations across all clients. Only the changed key-value pair is sent per operation.
How it works
SyncDictionary<TKey, TValue> wraps a standard dictionary and intercepts every write. When you set a key, remove an entry, or call Clear(), PurrNet queues a delta packet describing that operation. All observers apply the same operation on their local copy, keeping every client in sync without resending the full dictionary.
Late-joining clients receive the full current state on connect — no extra code needed.
Constructor Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
ownerAuth | bool | false | When true, only the current owner of the NetworkBehaviour can write to this dictionary. The server can always write regardless. |
sendIntervalInSeconds | float | 0 | Minimum time between sync packets. Use > 0 to throttle high-frequency updates such as per-frame score increments. |
Basic usage
using PurrNet;
using UnityEngine;
public class PlayerBuffSystem : NetworkBehaviour
{
// Maps buff ID → remaining duration in seconds
private SyncDictionary<int, float> _activeBuffs = new SyncDictionary<int, float>();
private void Awake()
{
_activeBuffs.onChanged += OnBuffChanged;
}
private void OnBuffChanged(SyncDictionaryChange<int, float> change)
{
switch (change.operation)
{
case SyncDictionaryOperation.Set:
// Key was added or its value was updated
BuffUI.ShowBuff(change.key, change.value);
break;
case SyncDictionaryOperation.Removed:
BuffUI.RemoveBuff(change.key);
break;
case SyncDictionaryOperation.Cleared:
BuffUI.ClearAll();
break;
}
}
// Server applies a buff to this player
public void ApplyBuff(int buffId, float duration)
{
if (!isServer) return;
_activeBuffs[buffId] = duration; // Set operation
}
public void RemoveBuff(int buffId)
{
if (!isServer) return;
_activeBuffs.Remove(buffId); // Removed operation
}
private void Update()
{
if (!isServer) return;
// Tick down all buff durations
var expired = new System.Collections.Generic.List<int>();
foreach (var kv in _activeBuffs)
{
_activeBuffs[kv.Key] = kv.Value - Time.deltaTime;
if (_activeBuffs[kv.Key] <= 0f)
expired.Add(kv.Key);
}
foreach (var id in expired)
_activeBuffs.Remove(id);
}
}SyncDictionaryChange properties
| Parameter | Type | Default | Description |
|---|---|---|---|
.operation | SyncDictionaryOperation | — | The type of change: Set (key added or updated), Removed (key deleted), or Cleared (all entries removed). |
.key | TKey | — | The dictionary key affected by this operation. Present for Set and Removed operations. |
.value | TValue | — | The new value for Set operations. For Removed and Cleared operations this field is the default value of TValue. |
Available operations
dict[key] = value— set or update a key; firesSetoperationRemove(key)— removes a key; firesRemovedoperationClear()— removes all entries; firesClearedoperationContainsKey(key),TryGetValue(key, out val)— read-only, not syncedCount— current number of entries
Situational example — real-time scoreboard
The scoreboard maps each player's PlayerID to their score. When the server updates a score, every client's UI refreshes through onChanged without any explicit broadcast.
using PurrNet;
using UnityEngine;
public class ScoreboardManager : NetworkBehaviour
{
// Server writes, all clients read
private SyncDictionary<PlayerID, int> _scores = new SyncDictionary<PlayerID, int>();
[SerializeField] private ScoreboardUI scoreboardUI;
private void Awake()
{
_scores.onChanged += OnScoresChanged;
}
protected override void OnSpawned(bool asServer)
{
base.OnSpawned(asServer);
if (asServer)
{
// Populate initial scores when the game starts
foreach (var player in networkManager.players)
_scores[player] = 0;
networkManager.onPlayerConnected += OnPlayerJoined;
networkManager.onPlayerDisconnected += OnPlayerLeft;
}
}
protected override void OnDespawned(bool asServer)
{
base.OnDespawned(asServer);
if (asServer)
{
networkManager.onPlayerConnected -= OnPlayerJoined;
networkManager.onPlayerDisconnected -= OnPlayerLeft;
}
}
// ---- Server-side mutations ----
public void AddScore(PlayerID player, int points)
{
if (!isServer) return;
if (!_scores.ContainsKey(player)) return;
_scores[player] = _scores[player] + points;
}
private void OnPlayerJoined(PlayerID player)
{
_scores[player] = 0;
}
private void OnPlayerLeft(PlayerID player)
{
_scores.Remove(player);
}
// ---- Client-side reaction ----
private void OnScoresChanged(SyncDictionaryChange<PlayerID, int> change)
{
// Rebuild the entire UI row for the affected player
switch (change.operation)
{
case SyncDictionaryOperation.Set:
scoreboardUI.UpdateRow(change.key, change.value);
break;
case SyncDictionaryOperation.Removed:
scoreboardUI.RemoveRow(change.key);
break;
case SyncDictionaryOperation.Cleared:
scoreboardUI.Clear();
break;
}
scoreboardUI.SortByScore(_scores);
}
}Mutable struct values require SetDirty
TValue is a mutable struct and you modify a field in place (e.g. _scores[id].kills++), the dictionary cannot detect the internal change. Read the struct, modify it, and reassign: var s = _scores[id]; s.kills++; _scores[id] = s; — or call _scores.SetDirty(id) after the mutation if direct assignment is inconvenient.Use simple keys
int, string, PlayerID) where possible. Complex struct keys require a custom equality comparer and add per-packet overhead because the key must be serialized alongside every delta operation.