Hi there, first of all i searched all google trying to found a easy fix for this with misleading results.
QUESTION
I have this:
[System.Serializable]
public class ItemModuleData {
}
public class ItemModule {
public ItemModuleData data;
}
[System.Serializable]
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;
a.data = anyModuleData;
PROBLEM
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.
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:
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.