很多情況下,一個組件可調整的屬性比較多,但是屬性之間又有一定的聯繫,最簡單的,當屬性type是類型typeA時,屬性width和height纔會起作用。
這時候,爲了界面的整潔和直觀,如果type的屬性不是typeA,那我們就沒必要暴露出width和height屬性。
默認的Inspector不能滿足這個需求,這就需要用Editor的OnInspectorGUI方法重新繪製顯示面板。
創建一個腳本類TestA.cs,幷包含一個枚舉類型TestType
[csharp]view plaincopy
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public enum TestType
- {
- typeA,
- typeB,
- }
- public class TestA : MonoBehaviour {
- public TestType type;
- public int width;
- public int height;
- // Use this for initialization
- void Start () {
- }
- }
然後在Editor文件夾下創建一個TestInspector.cs,繼承自Editor
[csharp]view plaincopy
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEditor;
- [CustomEditor(typeof(TestA))]
- public class TestInspector : Editor
- {
- private SerializedObject obj;
- private TestA testA;
- private SerializedProperty type;
- private SerializedProperty width;
- private SerializedProperty height;
- void OnEnable()
- {
- obj = new SerializedObject(target);
- width = obj.FindProperty("width");
- height = obj.FindProperty("height");
- }
- public override void OnInspectorGUI()
- {
- testA = (TestA)target;
- testA.type = (TestType)EditorGUILayout.EnumPopup("Type-", testA.type);
- if (testA.type == TestType.typeA)
- {
- EditorGUILayout.PropertyField(width);
- EditorGUILayout.PropertyField(height);
- }
- }
- }
-
注意引用UintyEditor和文件路徑,只要上層路徑的名字是Editor就可以,不比非得在根目錄的Editor裏。
代碼比較簡單,一目瞭然,就不講解了。下面是運行結果: