For a bit of context, I am trying to generate a random game object at a random position. I want to check if the distance between the random position and positions of pre-existing objects is at least the size of the player. If not then the random positon should be generated again. If the distance is greater than the size of the player then the object should be instantiated and added to created objects. However I am getting an index out of range error and I am unsure where and why.
int numberOfPillars = Random.Range(1,3);
for (int i = 0; i < numberOfPillars; i++)
{
Vector3 randomPos;
while (numberOfPillars != createdObjects.Count)
{
Debug.Log(createdObjects.Count);
randomPos = new Vector3(Random.Range(-12f, 12f), Random.Range(-7f, 7f), 0f);
for (int x = 0; x <= createdObjects.Count; x++)
{
if (Mathf.Abs(createdObjects[x].x - randomPos.x) >= playerSize || Mathf.Abs(createdObjects[x].y - randomPos.y) >= playerSize)
{
if (x == createdObjects.Count)
{
int selectedPillar = Random.Range(0, 4);
Instantiate(pillars[selectedPillar], randomPos, Quaternion.identity);
createdObjects.Add(randomPos);
}
}
}
}
}