Unity学习 —— Editor面板数据跟随枚举进行显示

Editor面板数据跟随枚举进行显示

 

Editor 代码

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

挂载代码

using UnityEngine;

public enum TestType
{
    typeA,
    typeB,
    typeC
}
public class TestA : MonoBehaviour
{
    public TestType type;
    [Header("All Show")]
    public int x;
    public int y;
    [Header("Only typeA")]
    public string a;
    public int b;
    [Header("Only typeB")]
    public string c;
    public int d;
    public int e;
    [Header("Only typeC")]
    public int f;
}
posted @   桜庭の猫  阅读(329)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示