Search Unity

Prefab script's references become null/missing when instantiated

Discussion in 'Scripting' started by badfitz66, Aug 5, 2020.

  1. badfitz66

    badfitz66

    Joined:
    Nov 21, 2013
    Posts:
    6
    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

    Code (CSharp):
    1.            
    2.             //Get the actual prefab from the assets (otherwise we'll be trying to instantiate the wrong thing)
    3.             GameObject basePrefab = PrefabUtility.GetCorrespondingObjectFromOriginalSource(newTile);
    4.             GameObject tile = PrefabUtility.InstantiatePrefab(basePrefab) as GameObject;
    5.  

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

    https://imgur.com/a/1lIKFvH (top is before prefab is instantiated, bottom is after)

    Why is this happening?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,914
    Where does the WallSide object that your prefab is referencing live? Is it another prefab? Is it an object in the hierarchy of basePrefab?
     
  3. badfitz66

    badfitz66

    Joined:
    Nov 21, 2013
    Posts:
    6
    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
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,914
    On this line:
    Code (CSharp):
    1. GameObject basePrefab = PrefabUtility.GetCorrespondingObjectFromOriginalSource(newTile);
    Has the "newTile" object been disconnected from the prefab? I'm reading the docs for https://docs.unity3d.com/ScriptReference/PrefabUtility.GetCorrespondingObjectFromSource.html 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?