M
M
Mirror
Search…
SyncDictionary
A SyncDictionary is an associative array containing an unordered list of key, value pairs. Keys and values can be any supported mirror type. By default we use .Net Dictionary which may impose additional constraints on the keys and values.
SyncDictionary works much like SyncLists: when you make a change on the server the change is propagated to all clients and the Callback is called. Only deltas are transmitted.

Usage

Add a field to your NetworkBehaviour class of type SyncDictionary.
SyncDictionary must be declared readonly and initialized in the constructor.
Note that by the time you subscribe to the callback, the dictionary will already be initialized, so you will not get a call for the initial data, only updates.

Simple Example

1
using UnityEngine;
2
using Mirror;
3
4
public struct Item
5
{
6
public string name;
7
public int hitPoints;
8
public int durability;
9
}
10
11
public class ExamplePlayer : NetworkBehaviour
12
{
13
public readonly SyncDictionary<string, Item> Equipment = new SyncDictionary<string, Item>();
14
15
public override void OnStartServer()
16
{
17
Equipment.Add("head", new Item { name = "Helmet", hitPoints = 10, durability = 20 });
18
Equipment.Add("body", new Item { name = "Epic Armor", hitPoints = 50, durability = 50 });
19
Equipment.Add("feet", new Item { name = "Sneakers", hitPoints = 3, durability = 40 });
20
Equipment.Add("hands", new Item { name = "Sword", hitPoints = 30, durability = 15 });
21
}
22
23
public override void OnStartClient()
24
{
25
// Equipment is already populated with anything the server set up
26
// but we can subscribe to the callback in case it is updated later on
27
equipment.Callback += OnEquipmentChange;
28
29
// Process initial SyncDictionary payload
30
foreach (KeyValuePair<string, Item> kvp in equipment)
31
OnEquipmentChange(SyncDictionary<string, Item>.Operation.OP_ADD, kvp.Key, kvp.Value);
32
}
33
34
void OnEquipmentChange(SyncDictionary<string, Item>.Operation op, string key, Item item)
35
{
36
switch (op)
37
{
38
case SyncIDictionary<string, Item>.Operation.OP_ADD:
39
// entry added
40
break;
41
case SyncIDictionary<string, Item>.Operation.OP_SET:
42
// entry changed
43
break;
44
case SyncIDictionary<string, Item>.Operation.OP_REMOVE:
45
// entry removed
46
break;
47
case SyncIDictionary<string, Item>.Operation.OP_CLEAR:
48
// Dictionary was cleared
49
break;
50
}
51
}
52
}
Copied!
By default, SyncDictionary uses a Dictionary to store it's data. If you want to use a different IDictionary implementation such as SortedList or SortedDictionary, then use SyncIDictionary and pass the dictionary instance you want it to use. For example:
1
public class ExamplePlayer : NetworkBehaviour
2
{
3
public readonly SyncIDictionary Equipment =
4
new SyncIDictionary(new SortedList());
5
}
Copied!
Last modified 5d ago
Copy link