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;
}
没有人应该止步不前,除非你觉得这样就很好了
分类:
Unity / 知识点
标签:
Unity
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了