- Home /
FindPropertyRelative for inherited classes isn't working
Hey! I've been working on a custom inspector for a project, but I can't seem to get properties from a derived class to either use with a property drawer or a custom inspector.
Here's a simple version of the code:
public class SomeClass : ScriptableObject {
public OtherClass otherClass; //which is set to DerivedClass or some other derivative of OtherClass
}
public class DerivedClass : OtherClass {
public DataType someVariable;
}
[CustomEditor(typeof(SomeClass))]
public class SomeClassCustomEditor : Editor {
public override void OnInspectorGUI() {
serializedObject.FindProperty("otherClass") != null
//but
serializedObject.FindProperty("otherClass").FindPropertyRelative("someVariable") == null //how do i get this?
}
}
As said, serializedObject.FindProperty("otherClass")
returns true, but serializedObject.FindProperty("otherClass").FindPropertyRelative("someVariable")
does not. Is there any way I could get around this or am I doing something wrong?
Answer by Bunny83 · Jun 02, 2020 at 01:49 AM
Even we don't have all necessary information we can already tell that what you try to do here simply doesn't work. We don't know what "OtherClass" actually is but there are only two possible general cases: Either OtherClass is a UnityEngine.Object derived class (a MonoBehaviour or ScriptableObject derived class) or it's just an ordinary Serializable .NET class. In both cases your code doesn't work.
If OtherClass is a MonoBehaviour or Scriptableobject derived class, the property "otherClass" inside "SomeClass" represents a serialized reference and you can not get any relative property from that since UnityEngine.Object derived classes are serialized seperately on their own.
If OtherClass is actually a Serializable .NET class your whole setup doesn't work since Unity's serialization system does not support polymorphism for custom serializable classes. Please have a look at the script serialisation documentation, especially the section:
When might the serializer behave unexpectedly?
In short: custom serializable classes behave like structs. The serialization system does not store any type information in the serialized data. So the type of custom serializable classes is determined by the field type. Therefore after deserialization your otherClass variable would always contain an "OtherClass" instance and never a "DerivedClass" instance.