Advertisement
romanilyin

SerializableDictionary

Aug 26th, 2022
936
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.01 KB | None | 0 0
  1. [Serializable]
  2.  public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
  3.  {
  4.      [SerializeField]
  5.      private List<TKey> keys = new List<TKey>();
  6.      
  7.      [SerializeField]
  8.      private List<TValue> values = new List<TValue>();
  9.      
  10.      // save the dictionary to lists
  11.      public void OnBeforeSerialize()
  12.      {
  13.          keys.Clear();
  14.          values.Clear();
  15.          foreach(KeyValuePair<TKey, TValue> pair in this)
  16.          {
  17.              keys.Add(pair.Key);
  18.              values.Add(pair.Value);
  19.          }
  20.      }
  21.      
  22.      // load dictionary from lists
  23.      public void OnAfterDeserialize()
  24.      {
  25.          this.Clear();
  26.  
  27.          if(keys.Count != values.Count)
  28.              throw new System.Exception(string.Format("there are {0} keys and {1} values after deserialization. Make sure that both key and value types are serializable."));
  29.  
  30.          for(int i = 0; i < keys.Count; i++)
  31.              this.Add(keys[i], values[i]);
  32.      }
  33.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement