1
votes

I have some block prefabs that I add to an array of game objects:

public GameObject[]blocks;

Each prefab has a BoxCollider2D, Script & Rigidbody2D components. But when I try to instantiate the prefab in the scene it doesn't appear to have the components attached?

Here is how I am instantiating the prefab:

for (int i = 0; i < 4; i++) 
{
     for (int j = 0; j < gridWidth; j++) 
     {
      blockClone = Instantiate (blocks [Random.Range (0, blocks.Length)] as GameObject, new Vector3 (j, -i-2, 0f), transform.rotation) as GameObject;
     }

}

What am I doing wrong?

1
If you've edited a prefab within your scene, make sure to click the Apply button at the top of the inspector tab. If you haven't clicked the Apply button, components and variables that do not match the prefab will be bolded. After pressing the Apply button, the bold lettering goes away as things now match the prefab.Chris McFarland
Although unrelated to your question, it should be worth noting that using as vs. directly casting may have unintended consequences unless you are aware of the functionality. See this question: stackoverflow.com/questions/132445/…user991710

1 Answers

1
votes

Make sure your prefab is actually updated to contain the BoxCollider2D and the Rigibody2D.

Change this line:

blockClone = Instantiate (blocks [Random.Range (0, blocks.Length)] as GameObject, 
             new Vector3 (j, -i-2, 0f), transform.rotation) as GameObject;

To:

blockClone = Instantiate(blocks [Random.Range (0, blocks.Length)], 
             new Vector3(j, -i-2, 0f), transform.rotation) as GameObject;

You don't need that extra as GameObject


If all else fails you can attach them to the prefab at run time using AddComponent.

  blockClone.AddComponent<BoxCollider2d>();

That should be your last option, but double check your prefab before you do that.