本文参考以下博客,以遍历的方式判断字段是否在Inspector中显示
Unity根据条件控制Inspector面板中的属性显示_Hello Mingo-CSDN博客
SerializedObject类_mozhi-CSDN博客
一、实现效果:
TestA类在Inspector的原本显示:
实现后的效果:
二、代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum TestType
{
typeA,
typeB,
typeC
}
public class TestA : MonoBehaviour
{
public TestType type;
[Header("都会显示")]
public int x;
public int y;
[Header("typeA时显示")]
public string a;
public int b;
[Header("typeB时显示")]
public string c;
public int d;
public int e;
[Header("typeC时显示")]
public int f;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
#if UNITY_EDITOR
[CustomEditor(typeof(TestA))]
public class TestInspector : Editor
{
private SerializedObject obj;
private TestA testA;
private SerializedProperty iterator;
private List<string> propertyNames;
private TestType tryGetValue;
private Dictionary<string, TestType> specialPropertys
= new Dictionary<string, TestType>
{
{ "a", TestType.typeA },//表示字段a只会在枚举值=typeA时显示
{ "b", TestType.typeA },
{ "c", TestType.typeB },
{ "d", TestType.typeB },
{ "e", TestType.typeB },
{ "f", TestType.typeC },
};
void OnEnable()
{
obj = new SerializedObject(target);
iterator = obj.GetIterator();
iterator.NextVisible(true);
propertyNames = new List<string>();
do
{
propertyNames.Add(iterator.name);
} while (iterator.NextVisible(false));
testA = (TestA)target;
}
public override void OnInspectorGUI()
{
obj.Update();
GUI.enabled = false;
foreach (var name in propertyNames)
{
if (specialPropertys.TryGetValue(name, out tryGetValue)
&& tryGetValue != testA.type)
continue;
EditorGUILayout.PropertyField(obj.FindProperty(name));
if (!GUI.enabled)//让第1次遍历到的 Script 属性为只读
GUI.enabled = true;
}
obj.ApplyModifiedProperties();
}
}
#endif