I am trying to use Polymorphism with data that is to be serialized and deserialized. However, it seems that the polymorphic properties are being lost on serialization:
// Serialize
[System.Serializable]
public ParentClass()
{
public string someString = "a string";
}
[System.Serializable]
public ChildClass() : ParentClass
{
public int someInt;
public ChildClass(int _someInt)
{
someInt = _someInt;
}
}
List<ParentClass> list = new List<ParentClass>();
list.Add(new ChildClass(5));
// Data is serialized
// Data is deserialized
Debug.Log(list[0].someString);
// Output: a string; Works as intended
Debug.Log((list[0] as ChildClass).someInt));
// Null Reference Exception
How can you properly serialize these classes in this case?