Unity中自定义 Inspector 面板

博客围绕游戏脚本展开,介绍将脚本挂到 GameObject 上的效果,重点探讨只在 Inspector 中显示部分变量的实现方法,给出 CustomInspector、LugsTestEditor 两个脚本内容,还提及隐藏特定字段的修改方式,并提供相关参考链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假如有以下代码:

 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 }

转载于:https://www.cnblogs.com/luguoshuai/p/10941160.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值