Hey everyone! this is my first post in this forum so i don’t know how to properly ask here, please bear with me haha.
I’ve recently realised that unity editor keeps old references of changed classes.
i.e. If I have a class with one exposed reference to an object and i decide to erase it, I can lately undo that change in code and the reference is kept in the editor.
So I want to ask, is it posible to do it with inheritance?
i.e If i have a base monobehaviour class full of references set on a GO, but later I want to create some other classes that inherits from it and reasign one of them to that GO, is it posible to keep its references, or even other classes references to that object? maybe a tool or an option to do that?
Thanks in advance!
So if I understood you correctly you have a base class that you attached to a gameobject and that is serialized and later you want to replace that component with a derived version? That’s actually possible ^^.
A MonoBehaviour component in Unity represents several things at once. First of all there’s of course the managed class you created. Besides that there’s a native representation on the C++ side and that’s also where the serialized data is stored. Whenever your scripts are recompiled, the managed side is completely destroyed and rebuild from the serialized data. You can actually exchange the managed class in the inspector. This can be done by switching the inspector into debug mode (rightclick the context menu at the top of the inspector and chose Debug). Now you should see the top field that is called “script” will become editable. It’s actually the reference to the MonoScript instance / your script file that this component represents. You can simply drag a different MonoBehaviour script onto that field and the component would essentially “transform” into that new class. Keep in mind to switch the inspector back to normal.
However if you talk about changing the type of a custom serializable class that is serialized inline inside a MonoBehaviour, that’s actually not really possible. First of all plain custom serializable classes inside MonoBehaviours do not support inheritance out-of-the-box. You can use the new SerializeReference attribute on a field. By doing this Unity does actually support inheritance and polymorphism, however it does not have any built-in way to specify the actual type you want to use. So you need to create some editor scripts to actually handle this.