Unity Inspector编辑器扩展,枚举显示中文,枚举值自定义显示内容

记录!Unity Inspector面板编辑器扩展,枚举显示中文,枚举值自定义显示内容,显示部分选项。效果如下:

Unity Inspector编辑器扩展,枚举显示中文,枚举值自定义显示内容_第1张图片

枚举类代码:

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,
}

扩展类代码:

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 m_displayNames = new List();

    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

你可能感兴趣的:(UnityEditor,unity,编辑器,游戏引擎)