The question is answered, right answer was accepted
How do I repeat a function until a certain condition is met?
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);
}
}
}
Answer by Darhkmir · Nov 09, 2021 at 04:01 PM
Never mind, I'm an idiot. I just had to make a loop inside the function that repeats a limited number of times, and if a position is found just break the loop.
Follow this Question
Related Questions
How to make object fall loop? 0 Answers
OnControllerColliderHit keeps looping... 0 Answers
Why is Collider.IsTouching not working in this sample? 0 Answers
Trying to get Points to accumulate in game 0 Answers
Player Transform Postion on Collision Javascript/C# 0 Answers