enum中使用中文 unity_Unity编辑器开发,使用CustomPropertyDrawer实现枚举中文显示

在Unity开发中,枚举常常被用到。但是Unity自身对于枚举值,并不能做好中文的支持。无论是Head或者ToolTip.如下例:

usingUnityEngine;public classEnumTest : MonoBehaviour

{publicEmAniType AniType;

}public enumEmAniType

{

Idle,

Walk,

Run,

Atk,

Hit,

Die

}

029c6c80474c5091cbbefbc209707d8c.png

第一步,定义一个Unity属性标签PropertyAttribute。

usingUnityEngine;public classEnumLabelAttribute : HeaderAttribute

{public EnumLabelAttribute(string header) : base(header)

{

}

}

这里没有继承PropertyAttribute,而是HeaderAttribute。原因是HeaderAttribute继承PropertyAttribute,而我想用到HeaderAttribute的header字段。当然我们也可以完全继承PropertyAttribute。

第二步,使用CustomPropertyDrawer。在Editor文件夹下创建一个脚本EnumLabelDrawer.cs。EnumLabelDrawer继承PropertyDrawer,并加上CustomPropertyDrawer标签。在复写OnGUI方法,通过C#的反射,获取到枚举中枚举值上的Head标签属性数据。最终将这些属性中的中文说明展示出来。

usingSystem.Collections.Generic;usingUnityEditor;usingUnityEngine;

[CustomPropertyDrawer(typeof(EnumLabelAttribute))]public classEnumLabelDrawer : PropertyDrawer

{private readonly List m_displayNames = new List();public override voidOnGUI(Rect position, SerializedProperty property, GUIContent label)

{var att =(EnumLabelAttribute)attribute;var type =property.serializedObject.targetObject.GetType();var field =type.GetField(property.name);var enumtype =field.FieldType;foreach (var enumName inproperty.enumNames)

{var enumfield =enumtype.GetField(enumName);var hds = enumfield.GetCustomAttributes(typeof(HeaderAttribute), false);

m_displayNames.Add(hds.Length<= 0 ? enumName : ((HeaderAttribute)hds[0]).header);

}

EditorGUI.BeginChangeCheck();var value =EditorGUI.Popup(position, att.header, property.enumValueIndex, m_displayNames.ToArray());if(EditorGUI.EndChangeCheck())

{

property.enumValueIndex=value;

}

}

}

第三步,更改原有的枚举和脚本字段。在枚举值上加上Header标签,在脚本的字段上增加EnumLabel标签。

usingUnityEngine;public classEnumTest : MonoBehaviour

{

[EnumLabel("动画类型")]publicEmAniType AniType;

}public enumEmAniType

{

[Header("待机")]

Idle,

[Header("走")]

Walk,

[Header("跑")]

Run,

[Header("攻击")]

Atk,

[Header("受击")]

Hit,

[Header("死亡")]

Die

}

看看效果

c58fd036e69b46a2929acce6d7b9f49b.png

原文:http://www.cnblogs.com/CodeGize/p/6892299.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值