問題:在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://answers.unity.com/questions/642431/dictionary-in-inspector.html
- http://www.sikiedu.com/course/93/task/2810/show