【Unity】序列化字典Dictionary的问题

问题:在C#脚本定义了public Dictionary字典,然而在编辑器检视面板Editor Inspector中看不到(即无法序列化字典)。即不能在编辑器中拖拽给字典赋值。

目标:检视面板Inspector拖拽给Dictionary字典赋值。

解决思路:先用结构体struct模拟Dictionary字典,用一个包含该结构体的public数组来存放GameObject预制体。Unity编辑器中拖拽给数组赋值后,再在脚本中遍历数组内容添加到字典中。
public class GameManager : MonoBehaviour
{
    // 甜品的种类
    public enum SweetsType
    {
        EMPTY,
        NORMAL
    }

    // 甜品预制体的字典,可通过甜品种类,查到对应的甜品游戏物体
    public Dictionary<SweetsType, GameObject> sweetPrefabDict;

    [System.Serializable]
    public struct SweetPrefab
    {
        public SweetsType type;
        public GameObject prefab;
    }

    public SweetPrefab[] sweetPrefabs;

    private void Start()
    {
        // 字典内容
        sweetPrefabDict = new Dictionary<SweetsType, GameObject>();
        for (int i = 0; i < sweetPrefabs.Length; i++)
        {
            if (!sweetPrefabDict.ContainsKey(sweetPrefabs[i].type))
            {
                sweetPrefabDict.Add(sweetPrefabs[i].type, sweetPrefabs[i].prefab);
            }
        }
    }
}  

最终,能在编辑器检视面板中看到数组后,拖拽给数组赋值,再在脚本中给字典赋值。


学习资料:

 
原文地址:https://www.cnblogs.com/guxin/p/unity-serialization-dictionary.html