Unity實現(xiàn)枚舉類型中文顯示
更新時間:2021年02月23日 16:42:06 作者:被代碼折磨的狗子
這篇文章主要為大家詳細介紹了Unity實現(xiàn)枚舉類型中文顯示,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
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 () {
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
c#使用EPPlus將圖片流嵌入到Excel實現(xiàn)示例
這篇文章主要為大家介紹了c#使用EPPlus將圖片流嵌入到Excel實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12
c#異步操作后臺運行(backgroundworker類)示例
這篇文章主要介紹了c#異步操作后臺運行(backgroundworker類)示例,需要的朋友可以參考下2014-04-04

