- Home /
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.
People in here put time to help each other from their own free/working time. So ins$$anonymous$$d of asking for code freely, you better try something out for yourself and if you stack anywhere paste your code to get help. People can put time in showing you what is wrong with your code or even help you reform it. But surely not to just hand you scripts from scratch when you put zero effort on your own.
boss i never asked for code, i only asked only for suggestionson how to accomplish it. since i have never tried it before, i needed some help on the concept. please read the question once again, i asked help on how to do and not the code.
Answer by Fohristiwhirl · Sep 05, 2014 at 02:06 PM
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.
Answer by OrbitGames · Sep 05, 2014 at 01:20 PM
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);
}
}
thanks for the help. this piece of code gave me the idea on how to work on. thanks.