1. 先有一個普通的 繼承自 MonoBehaviour 的腳本.
2. 創建一個 Editor 文件夾, 寫 關於 UnityEditor 的腳本 都要放在這個文件夾下,不然會編譯出錯.
具體的實現如下:
1 using UnityEngine; 2 using UnityEditor; 3 using System.Collections; 4 5 [CustomEditor(typeof(TestBehaviour))] // 這里是表示,這個Editor是哪個腳本的界面 6 [CanEditMultipleObjects] // 可以一起編輯多個物體 7 public class TestBehaviourInspector : Editor { // 繼承 Editor 類 8 // 這里是定義幾個你要去控制的那個腳本里參數. 9 // moveType 是一個 enum 類型 10 SerializedProperty isPlaying, Count, moveType; 11 12 // 初始化, 將剛聲明的參數與那個腳本里面的屬性相關聯 13 void OnEnable() { 14 isPlaying = serializedObject.FindProperty("isPlaying"); 15 Count = serializedObject.FindProperty("Count"); 16 moveType = serializedObject.FindProperty("moveType"); 17 } 18 19 // Editor GUI 具體界面在這里寫 20 public override void OnInspectorGUI() { 21 // 官方說要先這樣 22 serializedObject.Update(); 23 24 // 使用一個 垂直 布局 25 EditorGUILayout.BeginVertical(); 26 27 // 如果是選擇多個物體的情況下. 要先判斷一下,這個屬性上面的值是不是都相同,相同才可以一起改變 28 if (!isPlaying.hasMultipleDifferentValues) { 29 isPlaying.boolValue = EditorGUILayout.Toggle("Is Playing", isPlaying.boolValue); 30 } 31 32 // 這是如果處理 enum 類型 33 if (!moveType.hasMultipleDifferentValues) { 34 moveType.enumValueIndex = (int)(TestBehaviour.MoveType)EditorGUILayout.EnumPopup("Move Type", (TestBehaviour.MoveType)moveType.enumValueIndex); 35 } 36 37 if (!Count.hasMultipleDifferentValues) { 38 Count.intValue = EditorGUILayout.IntField("Count", Count.intValue); 39 40 // 還可以使用 Button 41 if (GUILayout.Button("Print Count")) { 42 Debug.Log(Count.intValue); 43 } 44 } 45 46 EditorGUILayout.EndVertical(); 47 48 // 官方說 要在這里這樣一下.應用所有的修改 49 serializedObject.ApplyModifiedProperties(); 50 } 51 }