Unity 枚举值在Inspector面板显示中文

浪尽此生 提交于 2019-12-03 15:10:24

Unity 枚举值在Inspector面板显示中文

一般给策划写编辑器时便于策划查看选择类型,将枚举值显示为中文,如下所示
在这里插入图片描述

代码如下

using UnityEngine;
using System;

#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

使用:

// 定义枚举
[Serializable]
public enum ObjectTypeEnum
{
    /// <summary>
    /// 一般物体
    /// </summary>
    [EnumAttirbute("一般物体")]
    GENERAL = 0,
    /// <summary>
    /// 桥
    /// </summary>
    [EnumAttirbute("桥")]
    BRIDGE,
}
public class ObjectDescribe : MonoBehaviour {
    // 定义枚举属性
    [EnumAttirbute("类型")]
    public ObjectTypeEnum objectType;
}

将 ObjectDescribe.cs 挂在 GameObject 上即可

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!