- Home /
Run Coroutine only once
Hi
I am making a small minigame and I want it so when I reach 50 points it will start to spawn the fast enemies. How would I do something like this? If I did it like this...
void Update(){
if(score >= 50){
StartCoroutine(SpawnFastEnemies());
}
}
... it would start the same coroutine several times. How do I do something like this?
Thanks
Answer by shadbags · Nov 20, 2014 at 11:12 PM
Couple of ways. If the coroutine is necessary, I'd create a flag (a simple boolean variable) in this file, called something like
bool fastWavesStarted = false;
Then, alter your code to use this flag, and once it's fired, the flag will stop the coroutine running many many times.
void Update(){
if(score >= 50 && fastWavesStarted == false){
StartCoroutine(SpawnFastEnemies());
fastWavesStarted = true;
}
}
This way, you start the coroutine, then immediately make it so it can't start again. If you DO want to restart it, you can just set the flag back to false.
I'm having a very weird problem with this approach... $$anonymous$$y flag is somehow being reset and the StartCoroutine method is being called exactly twice (for aparent reason). I'm trying to prevent a new instance of the coroutine while the previous one is still running. Here is my code:
void Update()
{
if (!IsRunning)
{
IsRunning = true;
StartCoroutine("$$anonymous$$oveToTarget");
}
}
I have used breakpoints to check exactly how the coroutine is flowing and in fact the line that sets the IsRunning
flag back to false is only running when the object has reached the destination and the routine ends (allowing it to be set in montion towards the next target). However, again using breakpoints, I found out that before the first instance of the coroutine calls IsRunning = false
, the Update method is called again and for some demonic reason the flag is reset to false! So it starts a second instance of the coroutine... And the weirdest, it only calls exactly two instances. What could it possibly be??
This is embarassing...
t turns out I didn't realize I had two instances of my script attached to the game object, so the second time the breakpoint was hit and the flag was "magically" reset it was actually a different instance of the entire $$anonymous$$onoBehaviour... I will soon delete my comment in shame and go cry at the corner...
I had the same problem with my project. Been trying to find a solution for the last 2 days. Yours worked like a charm! You have my eternal gratitude!!!
Your answer
Follow this Question
Related Questions
I'd like to move a cube without delay.(C#) 0 Answers
StartCorutine not Working 3 Answers
How to force Coroutine to finish 1 Answer
Is there a way to show a warning when a Coroutine is called directly? 0 Answers
Rotation: rotate by a defined angle 1 Answer