I’m having trouble with destroying a 2D array of instantiated Prefabs. I searched around here and there were many questions that were very similar but their answers simply do not work for me.
I’m making a grid of plane objects at run time. What i want to be able to do is generate a grid of a certain size, then be able to regenerate the grid at another size. the problem is, despite looping through the grid and calling Destroy on each one, it just keeps making a new grid on top of the grid already there.
Generation Code:
private void GenerateGrid()
{
for (int zz = 0; zz < gridWidthandHeight; zz++)
{
for (int xx = 0; xx < gridWidthandHeight; xx++)
{
grid[xx, zz] = (GameObject)Instantiate(_squarePrefab);
grid[xx, zz].transform.position = topLeftPosition +
new Vector3(squareDimensions.x * xx, 0, squareDimensions.z * zz);
}
}
}
Destruction Code:
private void DestroyGrid()
{
for (int zz = 0; zz < gridWidthandHeight; zz++)
{
for (int xx = 0; xx < gridWidthandHeight; xx++)
{
if (grid[xx, zz] != null)
{
Destroy(grid[xx, zz]);
}
}
}
}
I call the Destroy function before the generate function every time i call to make the grid:
public void BuildGridObject(int widthAndHeight)
{
if (widthAndHeight % 2 != 1)
{
widthAndHeight += 1;
}
gridWidthandHeight = widthAndHeight;
grid = new GameObject[gridWidthandHeight, gridWidthandHeight];
position = this.gameObject.transform.position;
squareDimensions = _squarePrefab.renderer.bounds.size;
topLeftPosition = position -
new Vector3(
(gridWidthandHeight * squareDimensions.x) / 2,
0,
(gridWidthandHeight * squareDimensions.z) / 2) +
new Vector3(
squareDimensions.x / 2,
0,
squareDimensions.z / 2);
DestroyGrid();
GenerateGrid();
bounds = new Bounds(position, new Vector3(squareDimensions.x * gridWidthandHeight, 1, squareDimensions.z * gridWidthandHeight));
}
I have A set to make a 21x21 grid, S to make a 31x31 grid, D to make a 41x41 grid and F to make a 51x51 grid.
Every time I press one of those keys it should get rid of the grid that’s there and make the one, but its obviously not doing that.
I’m building this game as a way to get myself familiarized with Unity, so there must be something i’m missing, but i can’t figure out what. The other answers to similar questions were things like destroying the rigid body and not the game object, but my grid is a grid of game objects, by everything I’ve found this should work.