# how to instantiate gameobjects in a 2d array.

am doing a match the card type game…i need help in instantiating game objects in a grid like pattern at run time using arrays.am trying to learn how to do it,but a little help on how to do it will be helpful. thanks in advance. for example like this. [32032-match+pair.jpg|32032]

untested piece of code

``````    //create GO prefab
//create 2d GameObject array named 2dArray

for (int x = 0; x < 4; x++)
{
for (int y = 0; y < 4; y++)
{
2Darray[x,y] = (GameObject) Instaniate(prefab,new Vector3(x,0,y),Quaternion.Identity);
}
}
``````

You don’t actually need a 2D array really. You could have a 1D array of game objects. Then the width and height of the grid grid to access it.

``````public class GridBuilder : MonoBehaviour {

public int gridWidth = 5;
public int gridHeight = 5;
public GameObject[] cells;
public GameObject prefab;

void Start ()
{
cells = new GameObject[gridWidth * gridHeight];

for (int y = 0; y < gridHeight; y++)
{
for (int x = 0; x < gridWidth; x++)
{
int index = x + y * gridWidth;
cells[index] = prefab;

GameObject.Instantiate(cells[index], new Vector3(x,y,0), Quaternion.identity);

}
}

}
}
``````

This solutions ignores important things you may need to consider such as spacing between cells. Using more than one prefab to create pairs. Then shuffle the array to create randomness and a different game each time.