SerializableDictionary.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.Serialization;
  4. using UnityEngine;
  5. namespace Unity.Cloud.Collaborate.Common
  6. {
  7. //http://answers.unity3d.com/answers/809221/view.html
  8. [Serializable]
  9. internal class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
  10. {
  11. [SerializeField]
  12. List<TKey> m_Keys = new List<TKey>();
  13. [SerializeField]
  14. List<TValue> m_Values = new List<TValue>();
  15. public SerializableDictionary()
  16. {
  17. }
  18. public SerializableDictionary(IDictionary<TKey, TValue> input) : base(input)
  19. {
  20. }
  21. // Save the dictionary to lists
  22. public void OnBeforeSerialize()
  23. {
  24. m_Keys.Clear();
  25. m_Values.Clear();
  26. foreach (var pair in this)
  27. {
  28. m_Keys.Add(pair.Key);
  29. m_Values.Add(pair.Value);
  30. }
  31. }
  32. // load dictionary from lists
  33. public void OnAfterDeserialize()
  34. {
  35. Clear();
  36. if (m_Keys.Count != m_Values.Count)
  37. {
  38. throw new SerializationException($"there are {m_Keys.Count} keys and {m_Values.Count} " +
  39. "values after deserialization. Make sure that both key and value types are serializable.");
  40. }
  41. for (var i = 0; i < m_Keys.Count; i++)
  42. {
  43. Add(m_Keys[i], m_Values[i]);
  44. }
  45. }
  46. }
  47. }