Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Instantiate returns null

Discussion in 'Scripting' started by therealdude, May 24, 2010.

  1. therealdude

    therealdude

    Joined:
    Mar 8, 2009
    Posts:
    10
    I have a GameObject named "CharacterCatalog". It's children are GameObject prefabs that I tag ("Player") to represent Characters. The code I have below used to work until I disabled a Mesh Renderer within my characters. The Instantiate call is now returning null as if my Prefabs are corrupted or something. Any ideas?

    I get an array of these characters with this:

    Code (csharp):
    1. maAvatarGameObjects = GameObject.FindGameObjectsWithTag("Player");
    2.  
    And I Instantiate a copy of the character with this:

    Code (csharp):
    1. public GameObject CreateAvatar (string sCurrentAvatar)
    2. {
    3.     foreach (GameObject go in maAvatarGameObjects)
    4.     {
    5.         Debug.Log("Comparing " + go.name + " to " + sCurrentAvatar);
    6.         if (go.name.Equals(sCurrentAvatar))
    7.             return (GameObject)Instantiate(go);
    8.     }
    9.        
    10.     return null;
    11. }
    12.  
     
  2. therealdude

    therealdude

    Joined:
    Mar 8, 2009
    Posts:
    10
    I have more information:

    If I create a public variable in my script and drag a prefab onto that variable, it looks fine in the inspector. When I hit play, it disappears from that variable. If I set the value from the dropdown while playing, it's able to instantiate. If I set the value from the dropdown while NOT playing, I get the same problem (it's empty when playing, and of course, Instantiate returns null).

    By the way, if I dump my array from FindGameObjectsWithTag, they are all valid GameObject objects.

    Something is fishy about this.
     
  3. therealdude

    therealdude

    Joined:
    Mar 8, 2009
    Posts:
    10
    I solved the problem by:

    1. Deleting the prefabs in the project (but not the ones in my Scene).
    2. Created new empty prefabs in my project.
    3. Dragged the instances in my Scene back onto the blank prefabs.

    It seems that I was right that the prefabs were corrupted because the instances in my Scene were the same objects essentially. In other words, I did not change the settings of any of the Scene objects.
     
  4. PixelFireXY

    PixelFireXY

    Joined:
    Nov 2, 2011
    Posts:
    56