Unity 根据枚举值控制Inspector面板中的属性显示

本文参考以下博客,以遍历的方式判断字段是否在Inspector中显示

Unity根据条件控制Inspector面板中的属性显示_Hello Mingo-CSDN博客

SerializedObject类_mozhi-CSDN博客

一、实现效果:

        TestA类在Inspector的原本显示:

        Unity 根据枚举值控制Inspector面板中的属性显示_第1张图片

        实现后的效果:

        Unity 根据枚举值控制Inspector面板中的属性显示_第2张图片

        Unity 根据枚举值控制Inspector面板中的属性显示_第3张图片

        Unity 根据枚举值控制Inspector面板中的属性显示_第4张图片

二、代码

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 propertyNames;
    private TestType tryGetValue;
    private Dictionary specialPropertys
        = new Dictionary
        {
            { "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();
        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

你可能感兴趣的:(unity)