SerializedDictionary.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Collections.Generic;
  3. namespace UnityEngine.Rendering
  4. {
  5. //
  6. // Unity can't serialize Dictionary so here's a custom wrapper that does. Note that you have to
  7. // extend it before it can be serialized as Unity won't serialized generic-based types either.
  8. //
  9. // Example:
  10. // public sealed class MyDictionary : SerializedDictionary<KeyType, ValueType> {}
  11. //
  12. /// <summary>
  13. /// Serialized Dictionary
  14. /// </summary>
  15. /// <typeparam name="K">Key Type</typeparam>
  16. /// <typeparam name="V">Value Type</typeparam>
  17. [Serializable]
  18. public class SerializedDictionary<K, V> : Dictionary<K, V>, ISerializationCallbackReceiver
  19. {
  20. [SerializeField]
  21. List<K> m_Keys = new List<K>();
  22. [SerializeField]
  23. List<V> m_Values = new List<V>();
  24. /// <summary>
  25. /// OnBeforeSerialize implementation.
  26. /// </summary>
  27. public void OnBeforeSerialize()
  28. {
  29. m_Keys.Clear();
  30. m_Values.Clear();
  31. foreach (var kvp in this)
  32. {
  33. m_Keys.Add(kvp.Key);
  34. m_Values.Add(kvp.Value);
  35. }
  36. }
  37. /// <summary>
  38. /// OnAfterDeserialize implementation.
  39. /// </summary>
  40. public void OnAfterDeserialize()
  41. {
  42. for (int i = 0; i < m_Keys.Count; i++)
  43. Add(m_Keys[i], m_Values[i]);
  44. m_Keys.Clear();
  45. m_Values.Clear();
  46. }
  47. }
  48. }