监听面板值的变化

监听面板值的变化,一旦变化执行相应的方法,效果如下:

Paste_Image.png
Paste_Image.png
监听面板值的变化_第1张图片
Paste_Image.png

效果就是这样的一个效果,具体运用的话,就看项目需求了。接下来看看实现代码。

using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif 
public class ObserveAttribute : PropertyAttribute
{
    public string[] callbackNames;

    public ObserveAttribute(params string[] callbackNames)
    {
        this.callbackNames = callbackNames;
    }
}


#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(ObserveAttribute))]
public class ObserveDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginChangeCheck();
        EditorGUI.PropertyField(position, property, label);
        if (EditorGUI.EndChangeCheck())
        {
            if (IsMonoBehaviour(property))
            {

                MonoBehaviour mono = (MonoBehaviour)property.serializedObject.targetObject;

                foreach (var callbackName in observeAttribute.callbackNames)
                {
                    mono.Invoke(callbackName, 0);
                }

            }
        }
    }

    bool IsMonoBehaviour(SerializedProperty property)
    {
        return property.serializedObject.targetObject.GetType().IsSubclassOf(typeof(MonoBehaviour));
    }

    ObserveAttribute observeAttribute
    {
        get
        {
            return (ObserveAttribute)attribute;
        }
    }
}
#endif
using UnityEngine;

public class ObserveExample : MonoBehaviour
{
    [Observe("Callback")] 
    public string
        hoge;

    [Observe("Callback", "Callback2")] 
    public Test
        test;

    public enum Test
    {
        Hoge,
        Fuga
    }

    public void Callback ()
    {
        Debug.Log ("call");
    }

    private void Callback2 ()
    {
        Debug.Log ("call2");
    }
}

你可能感兴趣的:(监听面板值的变化)