Skip to content

Instantly share code, notes, and snippets.

@Alexander-van-der-Zalm
Last active March 2, 2023 00:16
Show Gist options
  • Select an option

  • Save Alexander-van-der-Zalm/8079a84915dc1adb65761a0a0327f70d to your computer and use it in GitHub Desktop.

Select an option

Save Alexander-van-der-Zalm/8079a84915dc1adb65761a0a0327f70d to your computer and use it in GitHub Desktop.
Unity3D - PropertyAttribute - OnChanged Call a method (basic)
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
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