码迷,mamicode.com
首页 > 编程语言 > 详细

实现Unity对Dictionary的序列化

时间:2016-06-12 20:20:35      阅读:2208      评论:0      收藏:0      [点我收藏+]

标签:

 unity doc: http://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.OnBeforeSerialize.html

 1 using UnityEngine;
 2 using System.Collections.Generic;
 3 
 4 /// Usage:
 5 /// 
 6 /// [System.Serializable]
 7 /// class MyDictionary : SerializableDictionary<int, GameObject> {}
 8 /// public MyDictionary dic;
 9 ///
10 [System.Serializable]
11 public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
12 {
13     // We save the keys and values in two lists because Unity does understand those.
14     [SerializeField]
15     private List<TKey> _keys;
16     [SerializeField]
17     private List<TValue> _values;
18 
19     // Before the serialization we fill these lists
20     public void OnBeforeSerialize()
21     {
22         _keys = new List<TKey>(this.Count);
23         _values = new List<TValue>(this.Count);
24         foreach (var kvp in this)
25         {
26             _keys.Add(kvp.Key);
27             _values.Add(kvp.Value);
28         }
29     }
30 
31     // After the serialization we create the dictionary from the two lists
32     public void OnAfterDeserialize()
33     {
34         this.Clear();
35         int count = Mathf.Min(_keys.Count, _values.Count);
36         for (int i = 0; i < count; ++i)
37         {
38             this.Add(_keys[i], _values[i]);
39         }
40     }
41 }

 

实现Unity对Dictionary的序列化

标签:

原文地址:http://www.cnblogs.com/suoluo/p/5578618.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!