实现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 }
复制代码

 

posted @   桫椤  阅读(15556)  评论(3编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示