Unity中自定義 Inspector 面板


假如有以下代碼:

 1 using UnityEngine;
 2 using UnityEditor;
 3 
 4 public class LugsTest : MonoBehaviour
 5 {
 6     [SerializeField]
 7     bool isEnabled;
 8 
 9     [SerializeField]
10     string name;
11 }

將這個腳本直接掛到 GameObject 上的效果是:

這個是顯而易見的答案。如果現在有一個需求,只在 Inspector 中顯示代碼中的部分變量,該如何做呢?這個就是這里要實現的內容。

額外多出兩個腳本(其實多出一個就可以,只是這里想總結一套架構清晰的邏輯):

CustomInspector、LugsTestEditor

以下分別是兩個腳本的內容:

 1 using UnityEngine;
 2 using UnityEditor;
 3 
 4 public class CustomInspector : Editor
 5 {
 6     protected void DrawPropertyField(string filedName)
 7     {
 8         DrawPropertyField(filedName, true, true);  
 9     }
10 
11     protected void DrawPropertyField(string fieldName, bool isValid, bool isValidWarning)
12     {
13         WrapWithValidationColor(() =>
14         {
15             SerializedProperty property = serializedObject.FindProperty(fieldName);
16             EditorGUILayout.PropertyField(property);
17         }, isValid, isValidWarning);
18     }
19 
20     protected void WrapWithValidationColor(System.Action method, bool isValid, bool isValidWarning)
21     {
22         Color colorBackup = GUI.color;
23         if (isValid == false)
24         {
25             GUI.color = Color.red;
26         }
27         else if (isValidWarning == false)
28         {
29             GUI.color = Color.yellow;
30         }
31         method.Invoke();
32         GUI.color = colorBackup;
33     }
34 }

 對以上腳本中第 31 行內容不理解的可以閱讀: https://www.cnblogs.com/luguoshuai/p/10940879.html

 

 1 using UnityEditor;
 2 using UnityEngine;
 3 
 4 
 5 [CustomEditor(typeof(LugsTest))]
 6 public class LugsTestEditor : CustomInspector
 7 {
 8     public override void OnInspectorGUI()
 9     {
10         DrawPropertyField("isEnabled");
11 
12         if (GUI.changed)
13         {
14             serializedObject.ApplyModifiedProperties();
15         }
16     }
17 }

在工程中加入以上腳本后的結果是怎么樣的呢?

這個時候隱藏了 name 字段,如果同時隱藏定義的兩個字段,該如何?只需修改 LugsTestEditor 中的內容即可。

 1 using UnityEditor;
 2 using UnityEngine;
 3 
 4 
 5 [CustomEditor(typeof(LugsTest))]
 6 public class LugsTestEditor : CustomInspector
 7 {
 8     public override void OnInspectorGUI()
 9     {
10         //DrawPropertyField("isEnabled");
11         //DrawPropertyField("name");
12 
13         if (GUI.changed)
14         {
15             serializedObject.ApplyModifiedProperties();
16         }
17     }
18 }


免責聲明!

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



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