【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);
            }
        }
    }
}  

最終,能在編輯器檢視面板中看到數組后,拖拽給數組賦值,再在腳本中給字典賦值。


學習資料:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM