Unity Inspector editor extension, enumeration display in Chinese, enumeration value custom display content

Record! Unity Inspector panel editor extension, enumeration display in Chinese, enumeration value custom display content, display some options. The effect is as follows:

Enum class code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnumTest : MonoBehaviour
{
    [EnumAttackLevel("攻击级别")]
    public EAttackLevel level;
}

public enum EAttackLevel
{
    [Header("0空")]
    None,
    [Header("1低")]
    Low,
    [Header("2中")]
    Med,
    [Header("3高")]
    High,
}

Extended class code:

using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

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

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

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        var att = (EnumAttackLevelAttribute)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);
            if (enumfield.Name == "None")//不显示None
            {
                continue;
            }
            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 + 1;//因为我们隐藏了一个显示项None,这儿别忘了加1
            Debug.LogError("value " + property.enumValueIndex.ToString());
        }
    }
}

https://www.cnblogs.com/fengxing999/p/12559887.html

Guess you like

Origin blog.csdn.net/Ling_SevoL_Y/article/details/134041220