chenxin
2020-10-21 146e39c5ef6bb29927cb7c00d7708fceab30a724
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Reflection;
 
namespace MoreMountains.NiceVibrations
{
    [System.AttributeUsage(System.AttributeTargets.Field)]
    public class MMNVInspectorButtonAttribute : PropertyAttribute
    {
        public readonly string MethodName;
 
        public MMNVInspectorButtonAttribute(string MethodName)
        {
            this.MethodName = MethodName;
        }
    }
 
#if UNITY_EDITOR
    [CustomPropertyDrawer(typeof(MMNVInspectorButtonAttribute))]
    public class InspectorMMNVButtonPropertyDrawer : PropertyDrawer
    {
        private MethodInfo _eventMethodInfo = null;
 
        public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label)
        {
            MMNVInspectorButtonAttribute inspectorButtonAttribute = (MMNVInspectorButtonAttribute)attribute;
 
            float buttonLength = position.width;
            Rect buttonRect = new Rect(position.x, position.y, buttonLength, position.height);
            GUI.skin.button.alignment = TextAnchor.MiddleLeft;
 
            if (GUI.Button(buttonRect, inspectorButtonAttribute.MethodName))
            {
                System.Type eventOwnerType = prop.serializedObject.targetObject.GetType();
                string eventName = inspectorButtonAttribute.MethodName;
 
                if (_eventMethodInfo == null)
                {
                    _eventMethodInfo = eventOwnerType.GetMethod(eventName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                }
 
                if (_eventMethodInfo != null)
                {
                    _eventMethodInfo.Invoke(prop.serializedObject.targetObject, null);
                }
                else
                {
                    Debug.LogWarning(string.Format("InspectorButton: Unable to find method {0} in {1}", eventName, eventOwnerType));
                }
            }
        }
    }
#endif
}