I’m trying to make 3 objects spawn in 5 different locations randomly and I got stuck because the clones are overlapping and the random spawn doesn’t stop spawning. I want to make the spawner to spawn the clones in 5 different areas without overlapping and want the spawner to stop when all the areas are full.
Here’s my code.
public Transform[] spawnLocations;
public GameObject[] whatToSpawnClone;
int positionNumber;
int randomInt;
void Update()
{
SpawnRandom();
}
void SpawnRandom()
{
randomInt = Random.Range(0, whatToSpawnClone.Length);
Instantiate(whatToSpawnClone[randomInt], spawnLocations[0].position, spawnLocations[0].rotation);
if (positionNumber == 0)
{
Instantiate(whatToSpawnClone[randomInt], spawnLocations[0].position, spawnLocations[0].rotation);
positionNumber = 1;
}
else if (positionNumber == 1)
{
Instantiate(whatToSpawnClone[randomInt], spawnLocations[1].position, spawnLocations[1].rotation);
positionNumber = 2;
}
else if (positionNumber == 2)
{
Instantiate(whatToSpawnClone[randomInt], spawnLocations[2].position, spawnLocations[2].rotation);
positionNumber = 3;
}
else if (positionNumber == 3)
{
Instantiate(whatToSpawnClone[randomInt], spawnLocations[3].position, spawnLocations[3].rotation);
positionNumber = 4;
}
else if (positionNumber == 4)
{
Instantiate(whatToSpawnClone[randomInt], spawnLocations[4].position, spawnLocations[4].rotation);
positionNumber = 0;
}
}
}
You should move it into your Start method if you only want it to run once.
Also heres an example of an alternative implementation
###Example:
public List<Transform> Locations;
public List<GameObject> Items;
void Start()
{
foreach(var location in Locations)
{
InstantiateRandomObject(location);
}
}
private Object InstantiateRandomObject(Transform location)
{
var index = Random.Range(0, Items.Count);
return Object.Instantiate(Items[index], location.position, location.rotation);
}
If the object is used, will it fill the empty area?