很多情况下,一个组件可调整的属性比较多,但是属性之间又有一定的联系,最简单的,当属性type是类型typeA时,属性width和height才会起作用。
这时候,为了界面的整洁和直观,如果type的属性不是typeA,那我们就没必要暴露出width和height属性。
默认的Inspector不能满足这个需求,这就需要用Editor的OnInspectorGUI方法重新绘制显示面板。
创建一个脚本类TestA.cs,并包含一个枚举类型TestType
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
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里。
代码比较简单,一目了然,就不讲解了。下面是运行结果: