Krythic

Unity OnChangedCall

Apr 7th, 2023
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.65 KB | None | 0 0
  1. using System.Linq;
  2. using UnityEngine;
  3. using UnityEditor;
  4. using System.Reflection;
  5.  
  6. public class OnChangedCallAttribute : PropertyAttribute
  7. {
  8.     public string methodName;
  9.     public OnChangedCallAttribute(string methodNameNoArguments)
  10.     {
  11.         methodName = methodNameNoArguments;
  12.     }
  13. }
  14.  
  15. #if UNITY_EDITOR
  16.  
  17. [CustomPropertyDrawer(typeof(OnChangedCallAttribute))]
  18. public class OnChangedCallAttributePropertyDrawer : PropertyDrawer
  19. {
  20.     public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  21.     {
  22.         EditorGUI.BeginChangeCheck();
  23.         EditorGUI.PropertyField(position, property, label);
  24.         if (!EditorGUI.EndChangeCheck()) return;
  25.  
  26.         var targetObject = property.serializedObject.targetObject;
  27.  
  28.         OnChangedCallAttribute callAttribute = attribute as OnChangedCallAttribute;
  29.         var methodName = callAttribute?.methodName;
  30.  
  31.         var classType = targetObject.GetType();
  32.         var methodInfo = classType.GetMethods().FirstOrDefault(info => info.Name == methodName);
  33.  
  34.         // Update the serialized field
  35.         property.serializedObject.ApplyModifiedProperties();
  36.  
  37.         // If we found a public function with the given name that takes no parameters, invoke it
  38.         if (methodInfo != null && !methodInfo.GetParameters().Any())
  39.         {
  40.             methodInfo.Invoke(targetObject, null);
  41.         }
  42.         else
  43.         {
  44.             // TODO: Create proper exception
  45.             Debug.LogError($"OnChangedCall error : No public function taking no " +
  46.                            $"argument named {methodName} in class {classType.Name}");
  47.         }
  48.     }
  49. }
  50. #endif
  51.  
  52.  
Add Comment
Please, Sign In to add comment