23
2017
05

Unity缂栬緫鍣ㄥ紑鍙戯紝浣跨敤CustomPropertyDrawer瀹炵幇鏋氫妇涓枃鏄剧ず

        鍦║nity寮鍙戜腑锛屾灇涓惧父甯歌鐢ㄥ埌銆備絾鏄疷nity鑷韩瀵逛簬鏋氫妇鍊硷紝骞朵笉鑳藉仛濂戒腑鏂囩殑鏀寔銆傛棤璁烘槸Head鎴栬匱oolTip.濡備笅渚嬶細

using UnityEngine;

public class EnumTest : MonoBehaviour
{
    public EmAniType AniType;
}

public enum EmAniType
 {
     Idle,
     Walk,
     Run,
     Atk,
     Hit,
     Die
 }

QQ鎴浘20170523065015

        涓轰簡灏嗚繖浜涙灇涓惧煎彉鎴愪腑鏂囷紝杩欓噷浣跨敤浜咰ustomPropertyDrawer锛https://docs.unity3d.com/ScriptReference/CustomPropertyDrawer.html锛夈

        绗竴姝ワ紝瀹氫箟涓涓猆nity灞炴ф爣绛綪ropertyAttribute銆

using UnityEngine;

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

        杩欓噷娌℃湁缁ф壙PropertyAttribute锛岃屾槸HeaderAttribute銆傚師鍥犳槸HeaderAttribute缁ф壙PropertyAttribute锛岃屾垜鎯崇敤鍒癏eaderAttribute鐨刪eader瀛楁銆傚綋鐒舵垜浠篃鍙互瀹屽叏缁ф壙PropertyAttribute銆

        绗簩姝ワ紝浣跨敤CustomPropertyDrawer銆傚湪Editor鏂囦欢澶逛笅鍒涘缓涓涓剼鏈珽numLabelDrawer.cs銆侲numLabelDrawer缁ф壙PropertyDrawer锛屽苟鍔犱笂CustomPropertyDrawer鏍囩銆傚湪澶嶅啓OnGUI鏂规硶锛岄氳繃C#鐨勫弽灏勶紝鑾峰彇鍒版灇涓句腑鏋氫妇鍊间笂鐨凥ead鏍囩灞炴ф暟鎹傛渶缁堝皢杩欎簺灞炴т腑鐨勪腑鏂囪鏄庡睍绀哄嚭鏉ャ

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

[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;
        }
    }
}

        绗笁姝ワ紝鏇存敼鍘熸湁鐨勬灇涓惧拰鑴氭湰瀛楁銆傚湪鏋氫妇鍊间笂鍔犱笂Header鏍囩锛屽湪鑴氭湰鐨勫瓧娈典笂澧炲姞EnumLabel鏍囩銆

using UnityEngine;

public class EnumTest : MonoBehaviour
{
    [EnumLabel("鍔ㄧ敾绫诲瀷")]
    public EmAniType AniType;
}

public enum EmAniType
{
    [Header("寰呮満")]
    Idle,

    [Header("")]
    Walk,

    [Header("")]
    Run,

    [Header("鏀诲嚮")]
    Atk,

    [Header("鍙楀嚮")]
    Hit,

    [Header("姝讳骸")]
    Die
}

        鐪嬬湅鏁堟灉

QQ鎴浘20170523065123

芦 涓婁竴绡 涓嬩竴绡 禄