这篇文章主要为大家详细介绍了Unity实现枚举类型中文显示,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
Unity脚本中枚举类型在inspector面板中文显示,供大家参考,具体内容如下
效果:
工具脚本:ChineseEnumTool.cs
using System;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using System.Reflection;
using System.Text.RegularExpressions;
#endif
/// <summary>
/// 设置枚举名称
/// </summary>
#if UNITY_EDITOR
[AttributeUsage(AttributeTargets.Field)]
#endif
public class EnumAttirbute : PropertyAttribute
{
/// <summary>
/// 枚举名称
/// </summary>
public string name;
public EnumAttirbute(string name)
{
this.name = name;
}
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(EnumAttirbute))]
public class EnumNameDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
// 替换属性名称
EnumAttirbute enumAttirbute = (EnumAttirbute)attribute;
label.text = enumAttirbute.name;
bool isElement = Regex.IsMatch(property.displayName, "Element \\d+");
if (isElement)
{
label.text = property.displayName;
}
if (property.propertyType == SerializedPropertyType.Enum)
{
DrawEnum(position, property, label);
}
else
{
EditorGUI.PropertyField(position, property, label, true);
}
}
/// <summary>
/// 重新绘制枚举类型属性
/// </summary>
/// <param name="position"></param>
/// <param name="property"></param>
/// <param name="label"></param>
private void DrawEnum(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginChangeCheck();
Type type = fieldInfo.FieldType;
string[] names = property.enumNames;
string[] values = new string[names.Length];
while (type.IsArray)
{
type = type.GetElementType();
}
for (int i = 0; i < names.Length; ++i)
{
FieldInfo info = type.GetField(names[i]);
EnumAttirbute[] enumAttributes = (EnumAttirbute[])info.GetCustomAttributes(typeof(EnumAttirbute), false);
values[i] = enumAttributes.Length == 0 ? names[i] : enumAttributes[0].name;
}
int index = EditorGUI.Popup(position, label.text, property.enumValueIndex, values);
if (EditorGUI.EndChangeCheck() && index != -1)
{
property.enumValueIndex = index;
}
}
}
#endif
public class ChineseEnumTool : MonoBehaviour {
}
新建Text脚本测试
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//定义动物类
public enum Animal
{
[EnumAttirbute("小狗")]
dog,
[EnumAttirbute("小猫")]
cat,
[EnumAttirbute("老虎")]
tiger
}
public class Test : MonoBehaviour {
[EnumAttirbute("动物")]
public Animal animal;
void Start () {
}
void Update () {
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持得得之家。
沃梦达教程
本文标题为:Unity实现枚举类型中文显示


基础教程推荐
猜你喜欢
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01