- Home /
Unexpected coroutine behavior for simple timer
So I'm trying to implement power-ups in my game that last for a certain period of time.
One of them is a slow-mo, which I want to last for 20 seconds, not including time while paused.
I had a coroutine working yesterday but all of a sudden it's not working. Here's the code for the coroutine itself:
IEnumerator slow_mo_powerup(){
Debug.Log ("start"); //coroutine
Time.timeScale = slowMoScale; //currently 0.5f
float start = Time.realtimeSinceStartup; //this is timeScale independent
float timer = start;
while (timer < start + 20.0f) { //count 20 seconds
if (Time.timeScale != 0){ //don't count if paused
timer = Time.realtimeSinceStartup;
}
Debug.Log (timer - start);
yield return 0;
}
Time.timeScale = 1.0f;
Debug.Log ("end");
}
I call StartCoroutine in a different part of the script. Now, I have tried running this many times and each time, it starts and slows it down, logs "start". But then it only goes through the loop once, logs a very small decimal for (timer - start), and then somehow exits without going through the loop again OR completing the last two lines. It never logs "end" nor speeds back up.
Any ideas for why this isn't working??
Thanks
Answer by zach-r-d · Aug 10, 2015 at 07:16 PM
Try using "yield return null" instead of "yield return 0" to wait for the next frame. That's a UnityScript-ism that doesn't translate to C#.
I just tried this and it didn't change the behavior.
It logged "start" and then went through the loop once, logging "6.818771E-05", and then exited out of the coroutine completely without logging "end".
Answer by awesome98boy · Aug 11, 2015 at 06:44 PM
I think I have figured it out, in part thanks to zach.r.d
The script with the coroutine object on it is attached to the power object itself, so when you use your last powerup (as I was during testing), I scripted it to Destroy(gameObject). This, however, stopped the coroutine.
So I fixed it by waiting to destroy the powerup until the timer finishes.