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

 

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