using System; using System.Collections.Generic; namespace UnityEngine.Rendering { /// /// Unity can't serialize Dictionary so here's a custom wrapper that does. Note that you have to /// extend it before it can be serialized as Unity won't serialized generic-based types either. /// /// The key type /// The value /// /// public sealed class MyDictionary : SerializedDictionary<KeyType, ValueType> {} /// [Serializable] public class SerializedDictionary : SerializedDictionary { /// /// Conversion to serialize a key /// /// The key to serialize /// The Key that has been serialized public override K SerializeKey(K key) => key; /// /// Conversion to serialize a value /// /// The value /// The value public override V SerializeValue(V val) => val; /// /// Conversion to serialize a key /// /// The key to serialize /// The Key that has been serialized public override K DeserializeKey(K key) => key; /// /// Conversion to serialize a value /// /// The value /// The value public override V DeserializeValue(V val) => val; } /// /// Dictionary that can serialize keys and values as other types /// /// The key type /// The value type /// The type which the key will be serialized for /// The type which the value will be serialized for [Serializable] public abstract class SerializedDictionary : Dictionary, ISerializationCallbackReceiver { [SerializeField] List m_Keys = new List(); [SerializeField] List m_Values = new List(); /// /// From to /// /// They key in /// The key in public abstract SK SerializeKey(K key); /// /// From to /// /// The value in /// The value in public abstract SV SerializeValue(V value); /// /// From to /// /// They key in /// The key in public abstract K DeserializeKey(SK serializedKey); /// /// From to /// /// The value in /// The value in public abstract V DeserializeValue(SV serializedValue); /// /// OnBeforeSerialize implementation. /// public void OnBeforeSerialize() { m_Keys.Clear(); m_Values.Clear(); foreach (var kvp in this) { m_Keys.Add(SerializeKey(kvp.Key)); m_Values.Add(SerializeValue(kvp.Value)); } } /// /// OnAfterDeserialize implementation. /// public void OnAfterDeserialize() { for (int i = 0; i < m_Keys.Count; i++) Add(DeserializeKey(m_Keys[i]), DeserializeValue(m_Values[i])); m_Keys.Clear(); m_Values.Clear(); } } }