標(biāo)注:https://www.cnblogs.com/CodeGize/p/6892299.html
?在Unity開發(fā)中,枚舉常常被用到。但是Unity自身對(duì)于枚舉值,并不能做好中文的支持。無(wú)論是Head或者ToolTip.如下例:
using UnityEngine;publicclass EnumTest : MonoBehaviour
{
? ? public EmAniType AniType;
}publicenum EmAniType
{
? ? Idle,
? ? Walk,
? ? Run,
? ? Atk,
? ? Hit,
? ? Die
}

為了將這些枚舉值變成中文,這里使用了CustomPropertyDrawer(https://docs.unity3d.com/ScriptReference/CustomPropertyDrawer.html)。
??????? 第一步,定義一個(gè)Unity屬性標(biāo)簽PropertyAttribute。
using UnityEngine;publicclass EnumLabelAttribute : HeaderAttribute
{
? ? publicEnumLabelAttribute(stringheader) :base(header)
? ? {
? ? }
}
??????? 這里沒(méi)有繼承PropertyAttribute,而是HeaderAttribute。原因是HeaderAttribute繼承PropertyAttribute,而我想用到HeaderAttribute的header字段。當(dāng)然我們也可以完全繼承PropertyAttribute。
??????? 第二步,使用CustomPropertyDrawer。在Editor文件夾下創(chuàng)建一個(gè)腳本EnumLabelDrawer.cs。EnumLabelDrawer繼承PropertyDrawer,并加上CustomPropertyDrawer標(biāo)簽。在復(fù)寫OnGUI方法,通過(guò)C#的反射,獲取到枚舉中枚舉值上的Head標(biāo)簽屬性數(shù)據(jù)。最終將這些屬性中的中文說(shuō)明展示出來(lái)。
using System.Collections.Generic;using UnityEditor;using UnityEngine;
[CustomPropertyDrawer(typeof(EnumLabelAttribute))]publicclass EnumLabelDrawer : PropertyDrawer
{
? ? privatereadonlyList m_displayNames =newList();
? ? publicoverridevoid OnGUI(Rect position, SerializedProperty property, GUIContent label)
? ? {
? ? ? ? varatt = (EnumLabelAttribute)attribute;
? ? ? ? vartype = property.serializedObject.targetObject.GetType();
? ? ? ? varfield = type.GetField(property.name);
? ? ? ? varenumtype = field.FieldType;
? ? ? ? foreach(varenumNamein property.enumNames)
? ? ? ? {
? ? ? ? ? ? varenumfield = enumtype.GetField(enumName);
? ? ? ? ? ? varhds = enumfield.GetCustomAttributes(typeof(HeaderAttribute),false);
? ? ? ? ? ? m_displayNames.Add(hds.Length <=0? enumName : ((HeaderAttribute)hds[0]).header);
? ? ? ? }
? ? ? ? EditorGUI.BeginChangeCheck();
? ? ? ? varvalue = EditorGUI.Popup(position, att.header, property.enumValueIndex, m_displayNames.ToArray());
? ? ? ? if (EditorGUI.EndChangeCheck())
? ? ? ? {
? ? ? ? ? ? property.enumValueIndex = value;
? ? ? ? }
? ? }
}
??????? 第三步,更改原有的枚舉和腳本字段。在枚舉值上加上Header標(biāo)簽,在腳本的字段上增加EnumLabel標(biāo)簽。
using UnityEngine;publicclass EnumTest : MonoBehaviour
{
? ? [EnumLabel("動(dòng)畫類型")]
? ? public EmAniType AniType;
}publicenum EmAniType
{
? ? [Header("待機(jī)")]
? ? Idle,
? ? [Header("走")]
? ? Walk,
? ? [Header("跑")]
? ? Run,
? ? [Header("攻擊")]
? ? Atk,
? ? [Header("受擊")]
? ? Hit,
? ? [Header("死亡")]
? ? Die
}

??????? 看看效果
