Last active
March 2, 2023 00:16
-
-
Save Alexander-van-der-Zalm/8079a84915dc1adb65761a0a0327f70d to your computer and use it in GitHub Desktop.
Unity3D - PropertyAttribute - OnChanged Call a method (basic)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Linq; | |
| using UnityEngine; | |
| using UnityEditor; | |
| using System.Reflection; | |
| /// Feel free to us this. :) | |
| public class OnChangedCallAttribute : PropertyAttribute | |
| { | |
| public string methodName; | |
| public OnChangedCallAttribute(string methodNameNoArguments) | |
| { | |
| methodName = methodNameNoArguments; | |
| } | |
| } | |
| #if UNITY_EDITOR | |
| [CustomPropertyDrawer(typeof(OnChangedCallAttribute))] | |
| public class OnChangedCallAttributePropertyDrawer : PropertyDrawer | |
| { | |
| public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) | |
| { | |
| EditorGUI.BeginChangeCheck(); | |
| EditorGUI.PropertyField(position, property); | |
| if(EditorGUI.EndChangeCheck()) | |
| { | |
| OnChangedCallAttribute at = attribute as OnChangedCallAttribute; | |
| MethodInfo method = property.serializedObject.targetObject.GetType().GetMethods().Where(m => m.Name == at.methodName).First(); | |
| if (method != null && method.GetParameters().Count() == 0)// Only instantiate methods with 0 parameters | |
| method.Invoke(property.serializedObject.targetObject, null); | |
| } | |
| } | |
| } | |
| #endif |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| public class SimpleOnChangedCallTester : MonoBehaviour | |
| { | |
| [OnChangedCall("ImChanged")] | |
| public int TestMeForChanges = 0; | |
| public void ImChanged() | |
| { | |
| Debug.Log("I have changed to" + TestMeForChanges); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment