- Home /
Problem with creating randomized grid
I'm making a 2D grid with randomized sprites. But for some reason, my script will instantiate more GameObjects within a single for loop than is possible. I'm stuck with this problem and cannot solve it.
Here is some of my code
private void CreateGrid()
{
print("A");
for (int i = 0; i <= maxX; i++)
{
for (int k = 0; k <= maxY; k++)
{
if (i != maxX && k != 0)
{
int air = Random.Range(0, 100);
if (air <= 50)
{
int block = Random.Range(0, 100);
GameObject go = null;
if (block < 65)
{
go = blockTypes[1];
}
else if (block >= 65 && block <= 70)
{
go = blockTypes[0];
}
else if (block > 70 && block <= 80)
{
go = blockTypes[3];
}
else if (block > 80 && block <= 98)
{
go = blockTypes[2];
}
else if (block > 98)
{
go = blockTypes[4];
}
GameObject g = Instantiate(go, Vector3.zero, Quaternion.identity);
g.name = g.name.Replace("(Clone)", "");
g.transform.position = startPos + new Vector3(i * blockSize, k * blockSize, 0);
g.transform.localScale = Vector3.one * blockSize;
blocks.Add(g);
blockPos.Add(g.transform.position);
}
}
}
}
}
public void ResetGrid()
{
if (!regeningGrid)
{
regeningGrid = true;
for (int i = 0; i < blockPos.Count; i++)
{
GameObject g = blocks[i];
blocks.RemoveAt(i);
blockPos.RemoveAt(i);
Destroy(g);
}
print("C");
CreateGrid();
game.IncLevel();
regeningGrid = false;
}
}
What do you mean by my script will instantiate more GameObjects within a single for loop than is possible
? You haven't explained what your problem is. Also, how big are maxX and maxY?
Hey, since I don't quite have your variables and such to mess around with the script, could you describe exactly what the output of your CreateGrid function is?
Hi @Its$$anonymous$$hanny - I'd first try the loop in simple form something like:
private void CreateGrid()
{
for (int y = 0; y < maxY; y++)
{
for (int x = 0; x < maxX; x++)
{
Debug.Log("x:" + x + " y:" + y);
}
}
}
Then see if you still have problems;
For example your line: "if (i != maxX && k != 0)" only makes it so, that x can't be it's max value, so if you have 4, tile 3 in x-axis will be the last one.
Also, y-axis tile won't be created, when k is zero. So basically this is just convoluted way of removing rows and columns I think.
Also lines: "int air = Random.Range(0, 100);" and "if (air
But like @Em3rgency - said - you don't actually explain, what the problem is.