标签:obj int 枚举 private Unity using Inspector TestType public
本文参考以下博客,以遍历的方式判断字段是否在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
标签:obj,int,枚举,private,Unity,using,Inspector,TestType,public 来源: https://blog.csdn.net/weixin_43134411/article/details/120391188
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。