ObserveAttribute.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using UnityEngine;
  2. #if UNITY_EDITOR
  3. using UnityEditor;
  4. #endif
  5. public class ObserveAttribute : PropertyAttribute
  6. {
  7. public string[] callbackNames;
  8. public ObserveAttribute(params string[] callbackNames)
  9. {
  10. this.callbackNames = callbackNames;
  11. }
  12. }
  13. #if UNITY_EDITOR
  14. [CustomPropertyDrawer(typeof(ObserveAttribute))]
  15. public class ObserveDrawer : PropertyDrawer
  16. {
  17. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  18. {
  19. EditorGUI.BeginChangeCheck();
  20. EditorGUI.PropertyField(position, property, label);
  21. if (EditorGUI.EndChangeCheck())
  22. {
  23. if (IsMonoBehaviour(property))
  24. {
  25. MonoBehaviour mono = (MonoBehaviour)property.serializedObject.targetObject;
  26. foreach (var callbackName in observeAttribute.callbackNames)
  27. {
  28. mono.Invoke(callbackName, 0);
  29. }
  30. }
  31. }
  32. }
  33. bool IsMonoBehaviour(SerializedProperty property)
  34. {
  35. return property.serializedObject.targetObject.GetType().IsSubclassOf(typeof(MonoBehaviour));
  36. }
  37. ObserveAttribute observeAttribute
  38. {
  39. get
  40. {
  41. return (ObserveAttribute)attribute;
  42. }
  43. }
  44. }
  45. #endif