GetType() on prefab component returns wrong Type (polymorphism serialization)

Hi, I want to ask if somebody came across something similar, and if they found a solution.

I have ScriptableObject which holds prefabs, which can then be accessed by their type, in runtime. Everything works fine until I change to a different branch where somebody else added a new prefab. Then this prefab returns wrong type of Component instead of a type that was assigned to the prefabs list. Instantiation works as intended, but I need to know this type before instantiation.

Restarting Unity fixes this issue, but when working in a big team this solution is not ideal, and I would like to be able to fix it automatically.

public class Bar : ScriptableObject
{
    public List<Component> Prefabs;

    public void Foo()
    {
        for (int i = 0; i < Prefabs.Count; i++)
        {
            // This returns a type of Component instead of a concrete type
            Type type = Prefabs[i].GetType();
        }
    }
}

Wait a second. You changed your branch while you have your project open in Unity? Of course that would cause countless of issues. Unity has already loaded it’s asset database and instance IDs are already given out to objects in memory. So your main issue is changing branches here. If that other branch added a new prefab which suddenly is referenced on that scriptable object, it’s very unlikely that Unity will detect those “magic changes” in the right order.

So I would strongly recommend to not do that. Especially since git (I assume you use git?) actually preserves the file change date of the commit that you check out. So times could even go backwards in time.

This is an instance of an old-as-world issue of polymorphism meeting serialization.

Lucky for us, Unity introduced a solution to this not long time ago:

// Use SerializeReference if this field needs to hold both Apples and Oranges.
[SerializeField][SerializeReference] Fruit fruit1 = new Apple();
[SerializeField][SerializeReference] Fruit fruit2 = new Orange();