監(jiān)聽面板值的變化盖奈,一旦變化執(zhí)行相應(yīng)的方法混聊,效果如下:
Paste_Image.png
Paste_Image.png
Paste_Image.png
效果就是這樣的一個(gè)效果偏灿,具體運(yùn)用的話互广,就看項(xiàng)目需求了聪全。接下來看看實(shí)現(xiàn)代碼辉饱。
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");
}
}