- Home /
Why does Yield WaitForSeconds () only run once
Hi, I'm struggling to understand why yield WaitForSeconds (2) only waits for 2 seconds the first time then afterwards prints "Do 2 seconds later" each frame, what am I not understanding here?
Thanks for your time!
function Do () {
yield WaitForSeconds (2);
print("Do 2 seconds later");
}
Answer by fafase · Feb 14, 2013 at 11:25 AM
Because you are not preventing new calls you probably have it like this:
function Update(){
Do();
}
Even though you are delaying the printing, you get a new call of the Do function every frame. This should fix your issue:
var call:boolean = true;
function Update(){
if(call){
Do();
call = false;
}
}
function Do () {
yield WaitForSeconds (2);
print("Do 2 seconds later");
call = true;
}
Brilliant! I keep forgetting to do this. $$anonymous$$y failed logic is that even though Update() runs every frame the yield would stop the outside function.
Thanks for your help.
Actually it's a bad idea to restart the coroutine all the time. It adds overhead and garbage each time you call it. If you want it to continue place it in a loop and call it just once in Start:
// UnityScript
function Start(){
Do();
}
function Do() {
while(true) {
yield WaitForSeconds (2f);
print("Executed every 2 seconds");
}
}
Infinite loops are only bad if they don't have a yield inside. This coroutine will run forever but since it has a yield inside the loop everything is fine.
Your answer
Follow this Question
Related Questions
Mysteries of yield 1 Answer
yield WaitForSeconds not returning 1 Answer
Problem with 'animation.CrossFade' and 'fadeLength'. 0 Answers
Yield WaitForSeconds never finishes? 2 Answers
WaitForSeconds not running 2 Answers