- Home /
Making a fill take exactly n seconds to complete
I'm working on a timer class I can call for a whole bunch of different purposes, and as part of it I'm trying to write a function that will gradually draw a sprite with a radial fill such as to indicate the timer's progress- when the sprite is invisible, it isn't running, when it's completely drawn the timer has completed. Currently I'm running the timer in one coroutine, and the fill in another:
IEnumerator CountDown(float time){
countdownRunning = true;
StartCoroutine("CountDownAnimation",time);
yield return new WaitForSeconds(time);
Debug.Log ("Ding ding ding");
if(countdownRunning)
//do stuff
countdownRunning = false;
}
IEnumerator CountDownAnimation(float time){
float animationTime = time;
while (animationTime > 0) {
animationTime -= Time.deltaTime;
countdownSprite.fillAmount = animationTime/time;
}
yield return null;
}
The obvious problem is that since coroutines don't run once per frame, animationTime continually returns true and the sprite jumps instantly from 0% fill to 100% fill. Is there a very simple way that I'm missing to correctly set the fill each frame, given that the waitforseconds() on CountDown precludes setting it in the same loop that runs the timer?
Oh hey, I'm a fool, that works perfectly- if you want to put this in an answer I'll mark it right, either way thank you! :)
Answer by VesuvianPrime · Sep 19, 2014 at 09:27 PM
I think your mistake is putting the yield statement outside of the loop
Answer by Slev · Sep 19, 2014 at 09:23 PM
Inside of your while loop place a:
yield return new WaitForSeconds(n);
this will wait n seconds (n being a float that can be less than 1) before the loop resume again. Since you seem to be filling with detlaTime you should be able to use
yield return new WaitForSeconds(deltaTime)
That would make the loop take twice as long to complete. You don't need to WaitForSeconds to wait for the next frame
That fills smoothly and looks great, but it doesn't seem to sync up with the timer, if I feed them both a value of 2f the timer takes two seconds to finish, and the fill takes about 3... is that a problem with how I've structured things?
@VesuvianPrime well thanks for re$$anonymous$$ding why I never help anyone on these stack sites.
So I'm sorry if it's an obvious question, but without using WaitForSeconds what's the obvious way to hold execution of a coroutine until the next frame?
Your answer
Follow this Question
Related Questions
Game over when time reached 1 Answer
Start Coroutine after other has finished 4 Answers
Multiple Cars not working 1 Answer