I’m trying to write some editor scripts, but I keep running into some really weird behavior for FindPropertyRelative.
Let’s say I have these classes:
[Serializable]
public class SimpleClass : ScriptableObject
{
[SerializeField]
public int myField;
}
public class SimpleClassBehavior : MonoBehaviour
{
[SerializeField]
private SimpleClass simple;
}
[CustomEditor(typeof(SimpleClass))]
public class SimpleClassEditor : Editor
{
public override void OnInspectorGUI()
{
var myField = serializedObject.FindProperty("myField");
// This works fine
}
}
[CustomEditor(typeof(SimpleClassBehavior))]
public class SimpleClassBehaviorEditor : Editor
{
SerializedProperty simpleClass = null;
SerializedProperty myField = null;
void OnEnable()
{
simpleClass = serializedObject.FindProperty("simple");
// This works fine
myField = simpleClass.FindPropertyRelative("myField");
// This does NOT work. This returns null 100% of the time.
int myFieldInt = (simpleClass.objectReferenceValue as SimpleClass).myField;
// This works perfectly, but I shouldn't have to do this.
}
}
I’m having an issue where calling FindPropertyRelative returns null. I know the object I’m looking for exists, because I can get it in other ways.
This has been annoying me for too long, so I wrote up a “fix” version of the FindPropertyRelative function using Neovivacity’s solution. It has one important difference from the usual Unity-version of this function. It takes, as the last parameter a reference to a SerializedObject. You can start out with this value as null, and the function will create one (if needed). The important thing to remember is to apply changes to this SerializedObject, at the end of your Drawing functions.
If you spot any flaws or holes in the following, please let me know.