# How to stop objects spawning on top of each other

Im making a darts game where you have to pop some balloons that are floating upwards. The problem im having is that the balloons asre spawning on top of each other here is my code currently. The general idea i have found so far is to create a list and then add the objects to the list and for each instantiate check the positions of the objects.
How would i check through the list for the positions of the objects and then use that information to find a new position for the object?

if(Time.time >= _NextSpawn){

int objectsToSpawn = balloons;

``````		for(int i = 0; i < objectsToSpawn; i++){

int randomX = Random.Range(minX, maxX);
int randomY = Random.Range(minY, maxY);
int randomZ = Random.Range(minZ, maxZ);

Vector3 pos = new Vector3(randomX, randomY, randomZ);

}
``````

The easiest is a brute force approach of generating random position and comparing them to the positions of the object until you find a position that works. Example untested code:

``````Vector3 FindPos()
{
for (int i = 0; i < 1000; i++)
{
float randomX = Random.Range(minX, maxX);
float randomY = Random.Range(minY, maxY);
float randomZ = Random.Range(minZ, maxZ);
Vector3 pos = new Vector3(randomX, randomY, randomZ);
int j;
for (j = 0; j < balloons.count; j++) {
if (Vector3.Distance(pos, balloons[j].transform.position) < threshold)
break;
}
if (j >= balloons.count)
return pos;
}
return pos;
}
``````

Since sometimes there is no solution (too many object in too small a space), you want to limit the number of times you try. Here the limit is 1000.

Where should i put this code in my script? As of right now my code spawns 10 balloons every 10 seconds but im not sure how to utilise the code you have provided

void Update () {

``````	if(Time.time >= _NextSpawn){
int objectsToSpawn = redballoons;

for(int i = 0; i < objectsToSpawn; i++){
int randomX = Random.Range(minX, maxX);
int randomY = Random.Range(minY, maxY);
int randomZ = Random.Range(minZ, maxZ);

Vector3 pos = new Vector3(randomX, randomY, randomZ);

Instantiate(balloon, pos, rot);

}
``````