Skip to content

Instantly share code, notes, and snippets.

@Aaron8052
Last active February 20, 2023 23:21
Show Gist options
  • Save Aaron8052/d41f3f9b1dd1cb522987ff9f7e426aea to your computer and use it in GitHub Desktop.
Save Aaron8052/d41f3f9b1dd1cb522987ff9f7e426aea to your computer and use it in GitHub Desktop.
Unity Serializable Dictionary

通过声明此类型可实现Dictionary的序列化(可在inspector中显示出KeyValues)

使用方法

  • 声明成员 public SerializableDictionary<KeyType, ValueType> serializableDictionary = new();
  • 其余使用方法与 Dictionary 类完全一致
using System;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
{
[Serializable]
public struct KeyValue
{
public TKey key;
public TValue value;
public static implicit operator KeyValue(KeyValuePair<TKey, TValue> pair)
{
return new KeyValue()
{
key = pair.Key,
value = pair.Value
};
}
}
public List<KeyValue> keyValues = new();
public void OnBeforeSerialize()
{
if (keyValues.Count > Count)
AddNewValue();
else if (keyValues.Count < Count)
UpdateSerializedValues();
}
void UpdateSerializedValues()
{
keyValues.Clear();
foreach(var pair in this)
keyValues.Add(pair);
}
void AddNewValue()
{
var current = keyValues[^1];
TryAdd(current.key, current.value);
}
public void OnAfterDeserialize()
{
Clear();
for (var i = 0; keyValues != null && i < keyValues.Count; i++)
{
var current = keyValues[i];
TryAdd(current.key, current.value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment