I’m trying to make a random solar system thing, and most of it is completed, except for planets spawning on top of each other. Though I did find a solution to this by using Physics.Checksphere. I made a function that returns ‘true’ if the position is taken and ‘false’ if it’s empty (I tested it with debug.log). What I want to know now is how to make the function repeat if the position is taken, selecting another position and then checking again if it’s taken, but also having a fail-safe to stop it from causing an infinite loop.
private void CheckPlanet(string planetTag, float min, float max, int index) {
if (_planets[index].CompareTag(planetTag)) {
if (!GameObject.Find(_planets[index].name + "(Clone)"))
{
float yAxis = Random.Range(min, max);
Vector3 spawnPos = new Vector3(0, yAxis, 0);
if (PositionTaken(spawnPos)) {
// This is where it goes if the position is taken
} else {
InstantiatePlanet(yAxis, index);
}
} else {
int newIndex = Random.Range(0, _planets.Length);
CheckPlanets(newIndex);
}
}
}