Prefab script's references become null/missing when instantiated

I’ve been creating a in-editor 3D tilemap tool with autotiling features for the past few days and I’ve come across quite a big problem. All my tiles are prefabs, and have a script that controls autotiling.

To update a tile, first I create a mask based on it’s neighbours and then get the corrosponding ‘rule’ from a dictionary. The dictionary contains the new tile and some extra info. The problem occurs however when I instantiate the new tile. Here’s the code for that

            //Get the actual prefab from the assets (otherwise we'll be trying to instantiate the wrong thing)
            GameObject basePrefab = PrefabUtility.GetCorrespondingObjectFromOriginalSource(newTile);
            GameObject tile = PrefabUtility.InstantiatePrefab(basePrefab) as GameObject;

When instantiated, I noticed that the script attached to the prefab loses all references to objects. Here’s a before and after

Imgur: The magic of the Internet (top is before prefab is instantiated, bottom is after)

Why is this happening?

Where does the WallSide object that your prefab is referencing live? Is it another prefab? Is it an object in the hierarchy of basePrefab?

WallSide refers to a prefab in the asset files. I’ve proven this to myself multiple times as:

  • The scene is empty and thus it’s literally impossible for it to be referring to any scene object
  • Selecting the field highlights the prefab in the project file viewer

Also, keep in mind that the references only become null once I instantiate the prefab from a script. It does not become null if I just drag the tile into the scene view showing that this does seem to be a problem with either InstantiatePrefab or GetCorrospondingObjectFromOriginalSource

On this line:

GameObject basePrefab = PrefabUtility.GetCorrespondingObjectFromOriginalSource(newTile);

Has the “newTile” object been disconnected from the prefab? I’m reading the docs for Unity - Scripting API: PrefabUtility.GetCorrespondingObjectFromSource and it’s implying that the behavior is slightly different depending on if the object was disconnected from its prefab. Maybe there needs to be another step where you go from the object in the prefab to the prefab asset itself?