Unity根据条件控制Inspector面板中的属性显示

原文:https://blog.csdn.net/u010133610/article/details/55670800#commentBox

很多情况下,一个组件可调整的属性比较多,但是属性之间又有一定的联系,最简单的,当属性type是类型typeA时,属性width和height才会起作用。

这时候,为了界面的整洁和直观,如果type的属性不是typeA,那我们就没必要暴露出width和height属性。


默认的Inspector不能满足这个需求,这就需要用Editor的OnInspectorGUI方法重新绘制显示面板。


创建一个脚本类TestA.cs,并包含一个枚举类型TestType


using System.Collections;  
2.using System.Collections.Generic;  
3.using UnityEngine;  
4.  
5.public enum TestType  
6.{  
7.    typeA,  
8.    typeB,  
9.}  
10.  
11.public class TestA : MonoBehaviour {  
12.      
13.    public TestType type;  
14.  
15.    public int width;  
16.    public int height;  
17.  
18.    // Use this for initialization  
19.    void Start () {  
20.          
21.    }  
22.}  
然后在Editor文件夹下创建一个TestInspector.cs,继承自Editor
using System.Collections;  
2.using System.Collections.Generic;  
3.using UnityEngine;  
4.using UnityEditor;  
5.  
6.[CustomEditor(typeof(TestA))]  
7.public class TestInspector : Editor  
8.{  
9.    private SerializedObject obj;  
10.    private TestA testA;  
11.    private SerializedProperty type;  
12.    private SerializedProperty width;  
13.    private SerializedProperty height;  
14.      
15.    void OnEnable()  
16.    {  
17.        obj = new SerializedObject(target);  
18.        width = obj.FindProperty("width");  
19.        height = obj.FindProperty("height");  
20.    }  
21.      
22.    public override void OnInspectorGUI()  
23.    {  
24.        testA = (TestA)target;  
25.        testA.type = (TestType)EditorGUILayout.EnumPopup("Type-", testA.type);  
26.  
27.        if (testA.type == TestType.typeA)  
28.        {  
29.            EditorGUILayout.PropertyField(width);  
30.            EditorGUILayout.PropertyField(height);  
31.        }  
32.    }  
33.}  

注意引用UintyEditor和文件路径,只要上层路径的名字是Editor就可以,不比非得在根目录的Editor里。


代码比较简单,一目了然,就不讲解了。下面是运行结果:


obj.ApplyModifiedProperties();

最后把属性重新应用到原有的脚本中


  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值