實現Unity對Dictionary的序列化


若有嘗試過想在unity的inspector檢視面板中像List或者數組那樣可以編輯Dictionary變量的童鞋應該知道,Dictionary變量不會出現在inspector中,unity並不會直接序列化Dictionary類型,但實際上unity有提供接口使之可能:

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

注意其中的This interface should be used very carefully. Unity's serializer usually runs on the non main thread, while most of the Unity API can only be called from the main thread.

請慎用該方法,它不是線程安全的。

 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     {
      //官方例子有誤,去掉     
    }
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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM