SyncDictionary is an easy way to keep a Dictionary collection automatically synchronized over the network.
SyncDictionary supports all the functionality a normal dictionary would, just as SyncList supports List abilities.
Callbacks for SyncDictionary are similar to SyncList. And like other synchronization types changes are set immediately before the callback occurs.
privatereadonlySyncDictionary<NetworkConnection,string> _playerNames =new();privatevoidAwake(){_playerNames.OnChange+= _playerNames_OnChange;}//SyncDictionaries also include the asServer parameter.privatevoid_playerNames_OnChange(SyncDictionaryOperation op,NetworkConnection key,string value,bool asServer){/* Key will be provided for * Add, Remove, and Set. */switch (op) { //Adds key with value.caseSyncDictionaryOperation.Add:break; //Removes key.caseSyncDictionaryOperation.Remove:break; //Sets key to a new value.caseSyncDictionaryOperation.Set:break; //Clears the dictionary.caseSyncDictionaryOperation.Clear:break; //Like SyncList, indicates all operations are complete.caseSyncDictionaryOperation.Complete:break; }}
If you are using this SyncType with a container, such as a class or structure, and want to modify values within that container, you must set the value dirty. See the example below.
[System.Serializable]privatestructMyContainer{publicstring PlayerName;publicint Level;}privatereadonlySyncDictionary<int,MyContainer> _containers =new();privatevoidAwake(){MyContainer mc =newMyContainer { Level =5 };_containers[2] = mc;}[Server]privatevoidModifyContainer(){MyContainer mc =_containers[2]; //This will change the value locally but it will not synchronize to clients.mc.Level=10; //You may re-apply the value to the dictionary._containers[2] = mc; //Or set dirty on the value or key. Using the key is often more performant._containers.Dirty(2);}