1. 程式人生 > >unity編輯器顯示中文列舉

unity編輯器顯示中文列舉

先上效果圖


放在非 Editor 資料夾下

using UnityEngine;
using System;

[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field)]
public class EnumLabelAttribute : PropertyAttribute
{
    public string label;
    public new int[] order = new int[0];
    public EnumLabelAttribute(string label)
    {
        this.label = label;
    }

    public EnumLabelAttribute(string label, params int[] order)
    {
        this.label = label;
        this.order = order;
    }
}
放在 Editor 資料夾下
下面這個才是我寫噠

在這裡顯示列舉的中文Popup

using UnityEditor;
using System;
using System.Reflection;

public class EditorGUIEnumPopup : EditorWindow {
    
    public static object EnumPopup(string title, Enum selected)
    {
        int index = 0;
        var array = Enum.GetValues(selected.GetType());
        int length = array.Length;

        string[] enumString = new string[length];
        for (int i = 0; i < length; i++)
        {
            FieldInfo[] fields = selected.GetType().GetFields();
            foreach (FieldInfo field in fields)
            {
                if (field.Name.Equals(array.GetValue(i).ToString()))
                {
                    object[] objs = field.GetCustomAttributes(typeof(EnumLabelAttribute), true);
                    if (objs != null && objs.Length > 0)
                    {
                        enumString[i] = ((EnumLabelAttribute)objs[0]).label;
                    }
                }
            }
        }

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.PrefixLabel(title);
        index = EditorGUILayout.Popup(selected.GetHashCode(), enumString);
        EditorGUILayout.EndHorizontal();

        return Enum.ToObject(selected.GetType(), index);
    }
}