[CustomPropertyDrawer (typeof(OnChangeAttribute))]
public class OnChangePropertyDrawer : PropertyDrawer
{
public override void OnGUI (Rect position, SerializedProperty prop, GUIContent label)
{
EditorGUI.BeginChangeCheck ();
string val = EditorGUI.TextField (position, label, prop.stringValue);
if (EditorGUI.EndChangeCheck ()) {
// ... get instance of object that I'm changing (an instance of ObjectB)
// ... call a method on that instance
prop.stringValue = val;
}
}
}
When there’s a change to a property in the GUI, I’d like to be able to get the instance of the object that has changed.
Is there any way to get the reference to that instance?
EDIT:
The problem seems to be that the property my PropertyDrawer is drawing is part of an array of objects in another class.
public class ObjectA : MonoBehaviour {
public ObjectB[] objects;
}
[System.Serializable]
public class ObjectB {
[OnChange ("StringValue")] public int myProperty
}
So when I change myProperty in the inspector, the value of prop.serializedObject.targetObject in the PropertyDrawer class is an instance of type ObjectA. I want the instance of ObjectB that I’ve changed.
EDIT:
ObjectA is a MonoBehaviour class that I’ve added as a component to a GameObject. ObjectB is a generic, serializable class I defined, the instances of which are created in the inspector. I set the size of the array, and enter the properties of each instance shown in the Inspector.
If your class is a SerializedObject (or any child of Object), you can use property.objectReferenceValue to get a reference to it.
GameObject ob = property.objectReferenceValue as GameObject;
As vexe & codingChris point out, you can use PropertyDrawer.fieldInfo for all Serializable types:
GameObject ob = fieldInfo.GetValue(property.serializedObject.targetObject) as GameObject;
ObjectB ob = fieldInfo.GetValue(property.serializedObject.targetObject) as ObjectB;
All of these methods work even if your object is inside an array.
Demonstration of using this code:
[Demo]
public GameObject thing;
[CustomPropertyDrawer(typeof(DemoAttribute))]
public class DemoDrawer : PropertyDrawer {
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
EditorGUI.BeginProperty(position, label, property);
{
Debug.Log(string.Format("objectReferenceValue={0} fieldInfo={1}", property.objectReferenceValue, fieldInfo.GetValue(property.serializedObject.targetObject) as GameObject));
EditorGUI.PropertyField(position, property);
}
EditorGUI.EndProperty();
}
}