Implementing Dictionaries as Network Variables in Unity

I’ve been working on a project where I need to synchronize data between networked players, and I’m particularly interested in using dictionaries to manage certain aspects of the game state.

I’m wondering if there’s a way to implement dictionaries as network variables directly. Has anyone successfully achieved this, or is there a recommended approach for synchronizing dictionary data between clients and ensuring that new players receive this information upon joining?

It’s rather straightforward with INetworkSerializable. You can serialize keys and values into two separate lists and on the other end restore the lists in a dictionary.

HOWEVER I always warn of using collections as NetworkVariable because every time any change to the collection occurs the entire collection gets synchronized!

If you have ten entries it may not matter in terms of traffic. If you have hundreds, it would simply be foolish to waste that bandwidth. If it might be more (thousands?) because there is no hard cap in the game (think: player resources in a survival game) it could be game-breaking for longer game sessions.

It is a far better approach to use RPC calls like:

OnSetKeyValuePairServerRpc(object key, object value) { … }
OnRemoveKeyServerRpc(object key) { … }

Because RARELY do you change more than one item in a dictionary at any given time, right? :wink:

The former method either adds a new key if it does not exist, or changes the key’s value if the key already exists.
I used ‘object’ here but of course you can use whatever type you’re using. Ideally I’d make it a generic method but I can’t recall if NGO supports that.

2 Likes

Thank you very much, the only problem with using RPCs is the difficulty of getting the information back from the list or dictionary when someone new enters the room. That’s why I’m opting for NetworkVariables, any option with which I can keep the information every time someone enters the room and it doesn’t take up much bandwidth either?

Same as above, with a slight alteration:

OnSetKeyValuePairClientRpc(object key, object value) { … }
OnRemoveKeyClientRpc(object key) { … }

Basically the server relays the set and remove key/value RPCs to all clients. You just need to make sure that the client who tells the server to set or remove a key doesn’t change its dictionary directly but rather waits for the server to send the response (of course you can take that shortcut with appropriate caution, eg. removing an already removed key shouldn’t throw).

I had a stab at this using NetworkList as a guide. It seems to work, they’ll be some caveats with the key/value types so I went with INetworkSerializable to keep things relatively simple.

 public class NetDictionary<K,V> : NetworkVariableBase where K : INetworkSerializable, new() where V : INetworkSerializable, new()
    {
        Dictionary<K, V> dictionary;
        List<NetDictionaryEvent<K,V>> dirtyEvents;

        public delegate void OnDictionaryChangedDelegate(NetDictionaryEvent<K,V> changeEvent);
        public event OnDictionaryChangedDelegate OnDictionaryChanged;

        public NetDictionary(NetworkVariableReadPermission readPerm = DefaultReadPerm,
            NetworkVariableWritePermission writePerm = DefaultWritePerm) : base(readPerm, writePerm)
        {
            dictionary = new Dictionary<K, V>();
            dirtyEvents = new List<NetDictionaryEvent<K,V>>();
        }

        public override void ReadField(FastBufferReader reader)
        {
            dictionary.Clear();

            reader.ReadValueSafe<int>(out int count);

            Debug.Log($"NetDictionary ReadField length: {reader.Length} count: {count}");

            for (int i = 0; i < count; i++)
            {
                reader.ReadNetworkSerializable<K>(out K key);
                reader.ReadNetworkSerializable<V>(out V value);

                dictionary.Add(key, value);
            }
        }

        public override void WriteField(FastBufferWriter writer)
        {
            Debug.Log("NetDictionary WriteField count: " + dictionary.Count);

            writer.WriteValueSafe<int>(dictionary.Count);

            foreach (KeyValuePair<K, V> keyValue in dictionary)
            {
                writer.WriteNetworkSerializable<K>(keyValue.Key);
                writer.WriteNetworkSerializable<V>(keyValue.Value);
            }
        }

        public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta)
        {
            reader.ReadValueSafe(out int deltaCount);

            Debug.Log($"NetDictionary ReadDelta length: {reader.Length} count: {deltaCount}");

            for (int i = 0; i < deltaCount; i++)
            {
                reader.ReadValueSafe(out NetEventType eventType);
                switch (eventType)
                {
                    case NetEventType.Add:
                        reader.ReadValueSafe<K>(out K key);
                        reader.ReadValueSafe<V>(out V value);

                        Debug.Log($"NetDictionary ReadDelta {key} {value}");

                        dictionary.Add(key, value);

                        if (OnDictionaryChanged != null)
                        {
                            OnDictionaryChanged(new NetDictionaryEvent<K, V>
                            {
                                EventType = eventType,
                                Key = key,
                                Value = value
                            });
                        }
                        break;
                }
            }
        }

        public override void WriteDelta(FastBufferWriter writer)
        {
            Debug.Log("NetDictionary WriteDelta count: " + dirtyEvents.Count);

            writer.WriteValueSafe(dirtyEvents.Count);

            foreach (var dictionaryEvent in dirtyEvents)
            {
                Debug.Log("NetDictionary WriteDelta dirtyEvent: " + dictionaryEvent);

                writer.WriteValueSafe(dictionaryEvent.EventType);

                switch (dictionaryEvent.EventType)
                {
                    case NetEventType.Add:
                        writer.WriteValueSafe<K>(dictionaryEvent.Key);
                        writer.WriteValueSafe<V>(dictionaryEvent.Value);
                        break;
                }
            }
        }

        public void Add(K key, V value)
        {
            dictionary.Add(key, value);

            var listEvent = new NetDictionaryEvent<K, V>()
            {
                EventType = NetEventType.Add,
                Key = key,
                Value = value
            };

            HandleDictionaryEvent(listEvent);
        }

        private void HandleDictionaryEvent(NetDictionaryEvent<K, V> listEvent)
        {
            dirtyEvents.Add(listEvent);
            SetDirty(true);
            OnDictionaryChanged?.Invoke(listEvent);
        }

        public override void ResetDirty()
        {
            Debug.Log("NetDictionary ResetDirty");

            base.ResetDirty();
            if (dirtyEvents.Count > 0)
            {
                dirtyEvents.Clear();
            }
        }

        public override bool IsDirty()
        {
            Debug.Log("NetDictionary IsDirty");
            return base.IsDirty() || dirtyEvents.Count > 0;
        }

        public IEnumerator<KeyValuePair<K, V>> GetEnumerator()
        {
            return dictionary.GetEnumerator();
        }
    }

Perhaps we can trouble @NoelStephens_Unity to explain how to do this properly. :slight_smile:

1 Like
2 Likes

Thanks for your response! I’m also interested in the topic of NetworkDictionaries.

Could you clarify something for me - what class are you putting these methods onto? Something like this?

public class NetDictionary : NetworkBehavior { ... }

And does this class contain a private dictionary object that the RPCs are managing?

I might be misunderstanding, but I think the original question was about the scenario where, say, Client #3 joins the game several minutes after the game started, and after the dictionary-syncing RPCs have already fired. This late-joining client would not receive those RPCs, but would still need to get the up-to-date Dictionary data sync’d somehow.

1 Like

Don’t forget that you can always use NetworkBehaviour.OnSynchronize to create your own serialization for data that is set/updated via RPC. That is invoked when a NetworkObject is first spawned on the server side and when the server is synchronizing a newly joined client.

This seems interesting, but if I wanted to use a single Dictionary object to hold some shared game state, would I be able to synchronize that dictionary using the OnSynchronize serializer? My understanding is no since Dictionary is not serializable out-of-the-box, which leads me to think perhaps Unity is encouraging other patterns for storing shared state?

From my experience thus far, our goal has been to try to provide the tools that enable a wide variety of possibilities when it comes to making a netcode enabled Unity project. If you search for “C# serialize dictionary” you will indeed find many suggestions on how to go about doing this…but the bottom line is that all suggested paths do require some additional effort whether serializing in a non-netcode or netcode enabled application.

We have made it (or at least have put reasonable effort towards making it) such that the majority of commonly serialized types can be serialized with minimal effort. So, taking a dictionary into account, there are many solutions that involve using Json…but Json can be expensive in string format… which then you could opt to use binary json (newtonsoft.json.bson) to get a more condensed serialization. But then there is the issue with serializing only the deltas of the dictionary as opposed to the entire dictionary…not knowing what kind of game state that is being serialized…it could possibly be that there are other approaches to handling the synchronization of game state…but I would need to know more specifics behind what kind of data types would be used for the keys and the data types used for the values and things of that nature to provide any real alternative.

Of course, I always take a step back if a path I am taking seems more difficult than it really should be…while I can’t (as in cannot endorse) point to any one particular GitHub repository, there are already several Unity friendly serializable dictionary solutions…some of which could provide a good foundation to making a “netcode friendly” serializable dictionary.

We encourage creating. :slight_smile:

1 Like

Appreciate the response as it does help me understand the Unity platform better. I’m working on my first large game and navigating a lot of new frameworks :slight_smile: