This question was asked before in a similar way, but not it is not what I am trying to achieve.
My goal:
I am working with Unity 2019.4.15f1 LTS and I am trying to spawn some obstacles as Game Objects (rocks) in a Vector2 matrix with positions, but at the same time I am also spawning the object player needs to collect. I am trying to create an algorithm so there are not bad spawns such as 3 obstacles in a raw or obstacles with a single space inside them, or even the collectibles behind objects.
EDIT: In the code I am posting, the only thing I am trying to achieve is to avoid spawning 2 rocks with an empty space between them. I only want them to be aligned or distant
My system:
The code down here checks if a cell of the matrix generated from a Random.Range is empty and also matching my requirements and if so it spawns the obstacles and collectibles.
for(int i = 0; i < rocksToSpawn; i++)
{
do
{
RandomCol = Random.Range(0, nColoumns);
RandomRaw = Random.Range(0, nRaws);
} while (fullCells[RandomCol, RandomRaw] == true|| FullCells[RandomCol+ 2, RandomRaw] == true || fullCells[RandomCol- 2, RandomRaw] == true || fullCells[RandomCol, RandomRaw+ 2] == true || fullCells[RandomCol, RandomRaw-2] == true); //it will stay in the loop until it finds empy cell or the cell I want for the algorithm
Instantiate(rock, new Vector3(RandomCol+ movingGrid.position.x, -0.5f, RandomRaw+ movingGrid.position.z), Quaternion.identity, movingGrid);
fullCells[ColR, RigR] = true; //true values if cell has object
}
//here there is another part of the code that is the same and spawns collectibles
It is working fine without my "Algorithm" , rocks and collectibles spawn only in empty cells and it is like a charm. But when I run the code with the new algorithm...
The problem:
I get an IndexOutOfRangeException: Index was outside the bounds of the array.
the 90% of the times I start my code because he is searching for cells in the matrix like -1 or -2 or even higher than the lenght of the array because of the RandomCol + 2
. I was thinking of adding another loop that checks if RandomCol + 2 != null
but it is just too inefficient and I know I am missing something so maybe you can help me in some ways.
Thanks for everything.