打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
实现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>, ISerializationCallbackReceiver12 {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 lists20     public void OnBeforeSerialize()21     {      //官方例子有误,去掉     
    }30 31 // After the serialization we create the dictionary from the two lists32 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 }

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
泛型与反射
C#泛型字典类比较
《Shuttler.Net东写西读之一》BCL里Dictionary的缘分算法
U3d内存优化(二)之Dictonary
WorkflowRuntime.CreateWorkflow 方法 (System.Wor...
C#高手之路详解解析Hashtable、Dictionary、SortedDictiona...
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服