gameobject array unity code example

Example: unity array of gameobjects

If you want to create an array of this gameobject, you can do this as follows:

int Size = 10;     //Number of objects
GameObject[] Tiles = new GameObject[Size];
Let's assume you have created a prefab, called "Tile". If we want to initialize the array's gameobjects, we could do it like this:

//Loop for the entire size of the array, 10 in this case
for (int i = 0; i < Size; i++)
{
    //Create the game object
    Tiles[i] = GameObject.Instantiate (Resources.Load ("Tile")) as GameObject;  

    //Position it in the scene
    Tiles[i].transform.position = new Vector3(i * 0.32f, 0, 0);
}
If you assign the following script to the Start() function of a gameobject in your scene, you will see 10 Tile prefab objects appear when you Run your game.

Tags:

Misc Example