Derived Class Serialization

Hi there, first of all i searched all google trying to found a easy fix for this with misleading results.


I have this:

public class ItemModuleData {


public class ItemModule {
  public ItemModuleData data;

public class EquipableData : ItemModuleData {


public class EquipableModule : ItemModule {
 public new EquipableData data;

I want to serialize both classes (ItemModuleData and EquipableData), for do things like this:

ItemModule a; = anyModuleData;


Unity can’t serialize inherit class, and it will throw an error like this:

The same field name is serialized multiple times in the class or its parent class. This is not supported: Base(MonoBehaviour) data

I can’t also use ScriptableObject since i don’t want to have a lot of .assets in my project and it makes no sense in this case at least for me.

Thanks in advanced.

The accepted above answer is out of date with the introduction of the SerializeReference decorator. Adding this decorator to the above code will now produce the desired outcome:

[SerializeReference] ItemModule a;


[SerializeReference] public ItemModuleData data;

If you do a quick search about that topic you’ll find tons of other questions like those:

I’ve stopped counting how many times i’ve answered that question ^^.

In short: Unity does not support inheritance for custom serializable classes. Those classes are not serialized on their own but simply as “child data” of the containing MonoBehaviour / ScriptableObject. The type of an instance is not saved at all. Therefore if you store a derived class in a base class variable it will turn into a base class instance after deserialization.

Likewise since the custom classes aren’t stored as seperate instances you can’t have cross references. If two MonoBehaviour classes reference the same custom serializable class instance, after deserialization each will have their own instance. Again: Custom serializable classes are just a neat way to manage serialized fields in a MonoBehaviour.

Of course that’s only true for Unity’s serialization system.

@Bunny83 is correct as usual, but I recently discovered GitHub - jacobdufault/fullserializer: A robust JSON serialization framework that just works with support for all major Unity export platforms. and it is amazing so far. It handles inheritance for you.