Unity中實現字段/枚舉編輯器中顯示中文(中文枚舉、中文標籤)

在unity開發編輯器相關經常會碰到定義的字段顯示在Inspector是中文,枚舉也經常碰到顯示的是字段定義時候的英文,程序還好,但是如果編輯器交給策劃編輯,策劃的英文水平不可保證,會很頭大,所以還是有個中文標籤/中文枚舉會很方便。

效果如下:

話不多說,直接貼實現,Editor部分可自行拆分放到Editor文件下下,當前用宏做區分,HeaderComponent繼承自PropertyAttribute,再利用即可

1. 中文標籤,新建ChineseLabelAttribute.cs

/****************************************************
    Author:        Flamesky
    Mail:        [email protected]
    Date:        2022/2/24 10:48:36
    Function:    Nothing
*****************************************************/

using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class ChineseLabelAttribute : HeaderAttribute
{
    public ChineseLabelAttribute(string header) : base(header)
    {
    }
}

#if UNITY_EDITOR

[CustomPropertyDrawer(typeof(ChineseLabelAttribute))]
public class ChineseLabelDrawer : PropertyDrawer
{

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        var att = attribute as ChineseLabelAttribute;
        EditorGUI.PropertyField(position, property, new GUIContent(att.header), true);
    }
}
#endif

 

2. 中文枚舉,新建EnumLabelAttribute.cs

/****************************************************
    Author:        Flamesky
    Mail:        [email protected]
    Date:        2022/2/22 20:30:40
    Function:    Nothing
*****************************************************/

using UnityEngine;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class EnumLabelAttribute : HeaderAttribute
{
    public EnumLabelAttribute(string header) : base(header)
    {
    }
}

#if UNITY_EDITOR

[CustomPropertyDrawer(typeof(EnumLabelAttribute))]
public class EnumLabelDrawer : PropertyDrawer
{
    private readonly List<string> m_displayNames = new List<string>();

    public override void OnGUI(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 in property.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;
        }
    }
}
#endif

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章