- Home /
trying to delay a loop using yield - not working
Or I think more likely that I just don't know how to use "yield" so any help is appreciated. I couldn't find an existing answer that helped in my situation.
I'm looping through an array of objects in the scene and scoring them, but only want it to score every 3 seconds, not immediately. Here's my code:
static function StartScoring() { currentGameState = GameState.Counting;
for ( var countableObject : Rigidbody in FindObjectsOfType (Rigidbody) )
{
CountObject( countableObject );
yield WaitForSeconds( 3 );
}
}
Without the yield call, the CountObject() function appears to be called multiple times immediately as expected. With the yield call, the CountObject() function NEVER gets called at all, not even once. I don't understand why this is.
One thing I'm doing that maybe is making this interesting is I have a static GameManager object, so this function is static and Start Scoring is being called from another static function which is being called from a completely separate (non-static) game object. Is this a factor?
Answer by Eric5h5 · Jun 18, 2010 at 05:38 AM
The only way to get a static function to work as a coroutine is to explicitly start it with StartCoroutine().
Thanks. The next thing I ran into is that it wouldn't let me call StartCoroutine() unless I was inside a $$anonymous$$onoBehavior, which I guess I was not because I was in a static function trying to call a static function with StartCoroutine(). So to fix this I just set a boolean flag in my static function and let the Update() function (which is a $$anonymous$$onoBehavior) check the flag and call the coroutine. Bonus...I didn't have to use StartCoroutine() now because I made my StartScoring function be an instance function.
Your answer
Follow this Question
Related Questions
How to add delay before showing GUI Button? 3 Answers
Forced player reset not being delayed 1 Answer
Have a function wait unitl a boolean is false 1 Answer
Delay If statement in Update c# 2 Answers
Yield only working once? 0 Answers