SerializableDictionary.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. namespace Funly.SkyStudio
  6. {
  7. // Unity can't serialize generics other than List<T>. So we use this serializable dict,
  8. // You need to subclass this so that your top level class doesn't have templating. The base
  9. // class will handle storing and restoring the dict content.
  10. [Serializable]
  11. public class SerializableDictionary<K, V> : System.Object, ISerializationCallbackReceiver
  12. {
  13. [NonSerialized]
  14. public Dictionary<K, V> dict = new Dictionary<K, V>();
  15. [SerializeField]
  16. public List<K> m_Keys = new List<K>();
  17. [SerializeField]
  18. public List<V> m_Values = new List<V>();
  19. public void Clear()
  20. {
  21. dict.Clear();
  22. }
  23. public V this[K aKey]
  24. {
  25. get { return dict[aKey]; }
  26. set { dict[aKey] = value; }
  27. }
  28. // Move dict into the list which is serializable.
  29. public void OnBeforeSerialize()
  30. {
  31. m_Keys.Clear();
  32. m_Values.Clear();
  33. foreach (K aKey in dict.Keys) {
  34. m_Keys.Add(aKey);
  35. m_Values.Add(dict[aKey]);
  36. }
  37. }
  38. // Restore the dict using the list contents.
  39. public void OnAfterDeserialize()
  40. {
  41. if (m_Keys.Count != m_Values.Count) {
  42. Debug.LogError("Can't restore dictionry with unbalaned key/values");
  43. return;
  44. }
  45. dict.Clear();
  46. for (int i = 0; i < m_Keys.Count; i++) {
  47. dict[m_Keys[i]] = m_Values[i];
  48. }
  49. }
  50. }
  51. }