zrrz111

SerializableDictionary

Feb 19th, 2016
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4.  
  5. [System.Serializable] public class KeyDataMap : SerializableDictionary<string, KeyData> {}
  6. [System.Serializable] public class BodyMap : SerializableDictionary<string, ProceduralAnim.BodyPart> {}
  7.  
  8. [System.Serializable]
  9. public class SerializableDictionary<TKey, TValue> : ISerializationCallbackReceiver {
  10.     [SerializeField]
  11.     private List<TKey> keys = new List<TKey>();
  12.    
  13.     [SerializeField]
  14.     private List<TValue> values = new List<TValue>();
  15.  
  16.     public Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
  17.  
  18.     public void Add(TKey key, TValue value) {
  19.         dictionary.Add(key, value);
  20.     }
  21.  
  22.     public TValue this [TKey key] {
  23.         set{ dictionary[key] = value; }
  24.         get{ return dictionary[key]; }
  25.     }
  26.  
  27.     // save the dictionary to lists
  28.     public void OnBeforeSerialize() {
  29.         keys.Clear();
  30.         values.Clear();
  31.         foreach(KeyValuePair<TKey, TValue> pair in dictionary) {
  32.             keys.Add(pair.Key);
  33.             values.Add(pair.Value);
  34.         }
  35.     }
  36.    
  37.     // load dictionary from lists
  38.     public void OnAfterDeserialize() {
  39.         dictionary.Clear();
  40.        
  41.         if(keys.Count != values.Count)
  42.             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."));
  43. //      Debug.Log (this.GetType ());
  44.         for (int i = 0; i < Mathf.Min(keys.Count,values.Count); i++)
  45.             dictionary.Add(keys[i],values[i]);
  46.     }  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment