using System; using System.Collections.Generic; using System.Runtime.Serialization; using UnityEngine; namespace Unity.Cloud.Collaborate.Common { //http://answers.unity3d.com/answers/809221/view.html [Serializable] internal class SerializableDictionary : Dictionary, ISerializationCallbackReceiver { [SerializeField] List m_Keys = new List(); [SerializeField] List m_Values = new List(); public SerializableDictionary() { } public SerializableDictionary(IDictionary input) : base(input) { } // Save the dictionary to lists public void OnBeforeSerialize() { m_Keys.Clear(); m_Values.Clear(); foreach (var pair in this) { m_Keys.Add(pair.Key); m_Values.Add(pair.Value); } } // load dictionary from lists public void OnAfterDeserialize() { Clear(); if (m_Keys.Count != m_Values.Count) { throw new SerializationException($"there are {m_Keys.Count} keys and {m_Values.Count} " + "values after deserialization. Make sure that both key and value types are serializable."); } for (var i = 0; i < m_Keys.Count; i++) { Add(m_Keys[i], m_Values[i]); } } } }