字典序列化
在 Unity 中,标准的 C# 字典(Dictionary<TKey, TValue>
)是不能直接序列化的,因为 Unity 的序列化系统不支持非 Unity 序列化的集合类型。可以通过手写字典实现
效果:
实现步骤:
-
继承
ISerializationCallbackReceiver
接口自定义序列化和反序列化过程。-
序列化之前**—将数据保存到List**中
ISerializationCallbackReceiver.OnBeforeSerialize()
-
反序列化之后调用 — 从List中恢复数据
ISerializationCallbackReceiver.OnAfterDeserialize()
-
-
需导入序列化插件odin,否则无法在Inspector面板看到
- 地址:https://download.csdn.net/download/Xz616/89503957
代码:
public abstract class UnitySerializedDictionary<TKey, TValue> : Dictionary<TKey, TValue>,
ISerializationCallbackReceiver
{
[SerializeField, HideInInspector] private List<TKey> keyData = new List<TKey>();
[SerializeField, HideInInspector] private List<TValue> valueData = new List<TValue>();
/// <summary>
/// 反序列化之后调用 --- 从List中恢复数据
/// </summary>
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
this.Clear();
for (int i = 0; i < this.keyData.Count && i < this.valueData.Count; i++)
{
this[this.keyData[i]] = this.valueData[i];
}
}
/// <summary>
/// 序列化之前调用---将数据保存到List中
/// </summary>
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
this.keyData.Clear();
this.valueData.Clear();
foreach (var item in this)
{
this.keyData.Add(item.Key);
this.valueData.Add(item.Value);
}
}
}