Unity根據條件控制Inspector面板中的屬性顯示

很多情況下,一個組件可調整的屬性比較多,但是屬性之間又有一定的聯繫,最簡單的,當屬性type是類型typeA時,屬性width和height纔會起作用。

這時候,爲了界面的整潔和直觀,如果type的屬性不是typeA,那我們就沒必要暴露出width和height屬性。

默認的Inspector不能滿足這個需求,這就需要用Editor的OnInspectorGUI方法重新繪製顯示面板。

創建一個腳本類TestA.cs,幷包含一個枚舉類型TestType

[csharp]view plaincopy

  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4. public enum TestType  
  5. {  
  6.     typeA,  
  7.     typeB,  
  8. }  
  9. public class TestA : MonoBehaviour {  
  10.     public TestType type;  
  11.     public int width;  
  12.     public int height;  
  13.     // Use this for initialization  
  14.     void Start () {  
  15.     }  
  16. }  


然後在Editor文件夾下創建一個TestInspector.cs,繼承自Editor

[csharp]view plaincopy

  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4. using UnityEditor;  
  5. [CustomEditor(typeof(TestA))]  
  6. public class TestInspector : Editor  
  7. {  
  8.     private SerializedObject obj;  
  9.     private TestA testA;  
  10.     private SerializedProperty type;  
  11.     private SerializedProperty width;  
  12.     private SerializedProperty height;  
  13.     void OnEnable()  
  14.     {  
  15.         obj = new SerializedObject(target);  
  16.         width = obj.FindProperty("width");  
  17.         height = obj.FindProperty("height");  
  18.     }  
  19.     public override void OnInspectorGUI()  
  20.     {  
  21.         testA = (TestA)target;  
  22.         testA.type = (TestType)EditorGUILayout.EnumPopup("Type-", testA.type);  
  23.         if (testA.type == TestType.typeA)  
  24.         {  
  25.             EditorGUILayout.PropertyField(width);  
  26.             EditorGUILayout.PropertyField(height);  
  27.         }  
  28.     }  
  29. }  

注意引用UintyEditor和文件路徑,只要上層路徑的名字是Editor就可以,不比非得在根目錄的Editor裏。

代碼比較簡單,一目瞭然,就不講解了。下面是運行結果:



發佈了35 篇原創文章 · 獲贊 20 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章