- Home /
Calling method via reflection on parent asset inside PropertyDrawer
Im trying to make a PropertyDrawer that will call a method on the object when a field is set. I got it working for objects that are in the scene, but it wont work for assets (or at least not ScriptableObjects)
Here is the full code:
[CustomPropertyDrawer(typeof(CallbackAttribute))]
public class CallbackDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
EditorGUI.BeginChangeCheck();
var result = EditorGUI.ObjectField(position, label, property.objectReferenceValue, fieldInfo.FieldType, false);
if (EditorGUI.EndChangeCheck())
{
property.objectReferenceValue = result;
var method = property.serializedObject.targetObject.GetType().GetMethod((attribute as CallbackAttribute).MethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
object obj = property.serializedObject.targetObject;
method.Invoke(obj, null);
}
EditorGUI.EndProperty();
}
}
Inside the method that is called the field will not be set. I tried loading the asset manually via the AssetDatabase, but that didn't work either. Is this a bug?
The Property system is holding back the change until your method exits. You could try to bypass that by writing the change directly yourself, but you'd be liable to break things like multi-object editing and undo.
yes that why it fails, i fixed it as described in the answer, thanks!
Answer by Amimoller · Feb 05, 2014 at 08:19 PM
So the solution is to wait a few frames before calling the method. I did this by making a static class and marking it with [InitializeOnLoad] and registering for updates. Then i use this class to hold a queue of callbacks that it will wait a few frames before calling