Hello there, here is my problem:
I have a script that instantiates cells in a grid. When this script finishes the instantiation of all these cells, it places them into a Gameobject Array that I use later to give them an index depending of their position in the grid. The instantiation part of the code is not necessary for you to understand my issue, it’s just for the context.
I also have an in-game Inputfield used to change the size of my grid. Each time I set a new value in my Inputfield, my script automatically resizes my grid, destroys all of my previous cells and recreates them, then proceeds once again with their instantiation and their placement in my array.
So, here is my array at the start of the game :
At this moment, everything is normal. Then, I change the size of the grid, and my array gats the new cells with a GameObject.Find() :
See ? It adds the new cells as expected, but it seems to keep the slots of the ancient gameObjects, like if it was just increasing its size to store more datas. In my script however, I specifically added a line of code to resize my array to 0 just in case, so that it keeps only the new size of my grid.
Here is my code for the instantiation and allocation in my array (Note that I launch the instantiating method once in my Start() function) :
private void InstantiateCells() {
for (float y = posInit.y; y < posInit.y + grid.gridSizeHeight; y += grid.height)
{
for (float x = posInit.x; x < posInit.x + grid.gridSizeWidth; x += grid.width)
{
Instantiate(cellGrid, spawnPosition, Quaternion.identity, cellGridContainer);
spawnPosition = new Vector3(spawnPosition.x + grid.width, spawnPosition.y, spawnPosition.z);
}
spawnPosition = new Vector3(posInit.x + grid.width / 2f, spawnPosition.y + grid.height, spawnPosition.z);
}
allGridCells = GameObject.FindGameObjectsWithTag("GridCells");
}
And here is my code to reset my array and get ris of the ancient cells :
public void ResetCells()
{
for (int i = 0; i < allGridCells.Length; i++) {
Destroy(allGridCells[i]);
}
allGridCells = new GameObject[0];
posInit = Vector3.zero;
spawnPosition = new Vector3(posInit.x + grid.width / 2f, posInit.y + grid.height / 2f, spawnPosition.z);
InstantiateCells();
}
If you’re wondering, yes, the array DOES reinitialize itself in the Reset() function, and keeps its length of 0 until the GameObject.Find(). The result when I comment the line InstantiateCells() :
However, after that, it keeps its ancient length(for this example, 25), PLUS the new length allocated by the GameObject.Find(), which explains the size of 50.
I tried everything I knew. I used Lists and Linked Lists, I used AddRange(), RemoveAt(), InsertRange(), Clear(), etc… And it doesn’t work. I know the issue is somewhere with the GameObject.Find(), but I can’t figure out why it doesn’t start assigning the new cells at the 0 index, instead of the end of the array.
Thanks for your answer.