This series of for loops is supposed to loop through a series of x and y values, check if x is odd and if so go into another for loop. The goal of the next loop is to check if a previously instantiated object is in close proximity to the potential new object at x,y. But for some reason I keep getting an Index out of range error.
Whenever I try to run with this code, a single obstacle is spawned and then I see the error. Could this be because the Count of the list is changing but is not updated in the for loop declaration?
{
public List<GameObject> obstacles = new List<GameObject>();
private List<Vector2> lastObstaclesSpawned = new List<Vector2>();
for (int x = 0; x <= 32; x++)
{
for (int y = 0; y <= 32; y++)
{
for (int z = 0; z <= lastObstaclesSpawned.Count; z++)
{
if (lastObstaclesSpawned.Count == 0 || (Mathf.Abs(lastObstaclesSpawned[z - 1].x - x) + Mathf.Abs(lastObstaclesSpawned[z - 1].y - y)) >= 6)
{
counter++;
}
}
if (counter == lastObstaclesSpawned.Count + 1)
{
rand2 = Random.Range(0, 8);
lastObstaclesSpawned.Add(new Vector2(x, y));
Instantiate(obstacles[rand2], new Vector3(x, y, -1), Quaternion.identity);
}
}
}
counter = 0;
}