在Unity中序列化字典dic,通过插件 Odin Inspector

使用代码

来自插件的网站:
https://odininspector.com/tutorials/serialize-anything/serializing-dictionaries

代码内容
创建一个class 重命名为:UnitySerializedDictionary

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>();

    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];
		}
    }

    void ISerializationCallbackReceiver.OnBeforeSerialize()
    {
		this.keyData.Clear();
		this.valueData.Clear();

		foreach (var item in this)
		{
			this.keyData.Add(item.Key);
			this.valueData.Add(item.Value);
		}
    }
}

然后在MyScriptableObject 中进行调用

[Serializable]
public class KeyCodeGameObjectListDictionary : UnitySerializedDictionary<KeyCode, List<GameObject>> { }

[Serializable]
public class StringScriptableObjectDictionary : UnitySerializedDictionary<string, ScriptableObject> { }

[Serializable]
public class MyItemObjectDictionary : UnitySerializedDictionary<string, MyItem> { }


public class MyScriptableObject : ScriptableObject
{
	public KeyCodeGameObjectListDictionary KeyCodeMap;

	public StringScriptableObjectDictionary StringMap;

    public MyItemObjectDictionary MyItemObject;
}


/// 
/// 自己定义的对象
/// 
[Serializable]
public class MyItem 
{
    public string Name;

    public int Id;
    public string Describe { get; set; }
    public int Type { get; set; }

}

效果:
在Unity中序列化字典dic,通过插件 Odin Inspector_第1张图片

你可能感兴趣的:(Unity,unity,游戏引擎)