- Home /
Coroutine stops when changing bool
Hi!
I have a coroutine that spawns my enemies and to make so it doesn't spawn like 500 of them, I have a simple check for that. This is the check code.
GameObject[] allZombies = GameObject.FindGameObjectsWithTag("Enemy");
if(allZombies.Length >= maxZombies){
spawning = false;
} else {
spawning = true;
}
It basically checks for the amount of zombies and if it is above max zombies, it sets the spawning bool to false and when there aren't enough zombies it sets it to true. But when this happens the coroutine stops. It uses a basic while(spawning == true) to spawn stuff. What can I do for this to keep going?
Thanks
Answer by Slev · Nov 21, 2014 at 03:32 PM
The Coroutine stops because it has reached the end of its function
while (spawning == true) {
//do stuff
}
//leave function
Instead what you want to do is:
while (true) { //or some other control value
if (spawning) {
//stuff
}
else {
//different stuff
}
}
Coroutines can run infitely as long as you use yield returns.
I tested this out. I changed
while(spawning == true){
GameObject spawnpoint = spawnPoints[Random.Range(0, spawnPoints.Length)];
Instantiate(normalZombie, spawnpoint.transform.position, Quaternion.identity);
yield return new WaitForSeconds(normalZombieDelay);
}
to
while(true){
if(spawning == true){
GameObject spawnpoint = spawnPoints[Random.Range(0, spawnPoints.Length)];
Instantiate(normalZombie, spawnpoint.transform.position, Quaternion.identity);
yield return new WaitForSeconds(normalZombieDelay);
}
}
When I tried to play the game it crashed the editor.
@Real$$anonymous$$TG Yeah you need to have a yield return outside of the if, right now if that if fails your coroutine keeps cycling trying to find a yield to return to the iterator.
@Slev I'm sorry but I have not done anything like this before so I need some help. I have added a return true; under the if statement but that doesn't do anything. It spawns one enemy and then stops. I also tried with return false;. What should I put?
EDIT: Just noticed you said yield return. I did try and put yield return; but that just gives me an error. So, what can I put?
@Real$$anonymous$$TG I would do it like this:
while(true){
if(spawning == true){
GameObject spawnpoint = spawnPoints[Random.Range(0, spawnPoints.Length)];
Instantiate(normalZombie, spawnpoint.transform.position, Quaternion.identity);
yield return new WaitForSeconds(normalZombieDelay);
}
else {
yield return null; //or some variation with a wait
}
}
Your answer
Follow this Question
Related Questions
StopCoroutine() is not stopping my coroutines 1 Answer
C# while within foreach doesn't complete 2 Answers
How to wait for Coroutine to finish? 2 Answers
Please help with While Loops 1 Answer
How to solve while loop lags 1 Answer