[Serializable] class A { }
[Serializable] class B : A { }
[Serializable] class C : A { }
public class MyComponent : MonoBehaviour
{
[SerializeReference]
A data;
[ContextMenu("Set Data")]
void SetData()
{
Undo.RecordObject(this, "Set Data");
data = new B();
}
}
Add MyComponent to a GameObject, select “Set Data”, then save the project;
Delete the definition of class B, modify “data = new B()” to “data = new C()” in SetData();
select “Set Data” again, save the project;
Reopen the project, data is not saved, in fact you can not save new data any more.
Thanks, Undo.RecordObject is used for Undo command, I know this. My question is, you can not save new data if old class deleted, but if change data without deleting old class, then you can save it.
I am assuming classes B and C have additional stuff built ontop of A. If the data you are intending to keep is unique to B or C, then they wont be saved by the data variable of type A. It should save data that can be held by A if you cast B or C into A.
Inheritance in this instance should be viewed as a one-way street, the base is unable to keep properties unique to its inheritors.
If what I’ve hypothesized isn’t the case however, then I am also stumped.
Yes, but it also ensures that the data is serialized, which is it’s main purpose. You can not simply modify instance data and expect unity to magically serialize that data.
Also as spiney199 said, it’s relevant where this data field is used and where the contained object is stored.
After you set the new data and save it, open the scene file with a text editor, you will find that the saved data type is still the old type (class B), the new data is not saved. In fact, YOU CAN NOT SAVE NEW DATA FOREVER!