2019-01-10Unity編輯器開發(fā),使用CustomPropertyDrawer實(shí)現(xiàn)枚舉中文顯示

標(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

}

??????? 看看效果

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容