I have a problem with serialization, in Unity (using C#).
I have the following classes (the arrows indicate inheritance):
Vehicle
(abstract) <- Car
(abstract) <- Sedan
and
Vehicle
(abstract) <- MotorBike
The vehicle class inherits from MonoBehavior
.
I have some gameobjects (prefabs), that I attached the classed to. I only use the non abstract classes (i.e. MotorBike
and Sedan
).
My problem is this:
I want to serialize the data stored within these classes, to be able to save/load. (I use BinaryFormatter
for this.) The problem is, MonoBehavior
isn't serializable.
All I want is to serialize the data within the vehicle classes, and (upon loading the data) pass that to my Vehicle Factory class, to re-instantiate the prefabs, with the deserialized data. So, I'm not really interested in whatever is stored in the MonoBehavior part.
What I've tried so far:
Using a separate Data class, but this causes all kinds of problems and I would need to create a child data class for each of my Vehicle classes. And I would need to make the Vehicle class Generic, to indicate which Data class it needs to use, which would require me to use the Generic Type in every place I use the Vehicle type.
Also, I tried to make a SerializationSurrogate for MonoBehaviour, but this didn't work out, because there are numerous other Types that would need a surrogate. And since I'm not interested in the MonoBehaviour, but only in the Vehicle Class and it's child classes, this seemed to be too complex to try.
So, my question is: Does anybody know a way to handle this?