- Home /
Create a countdown in C# (inside Coroutine)
I'm making a circular countdown timer, and I already have the sprites and the stuff ready to be used. My problem is just making the timer inside a coroutine (it will be started after a level finishes loading), so I need to count X seconds inside it and display them by reducing the countdown Image fill. How do I make time count inside a coroutine and get how much time is left? (using the update function is a no because the class I'm working at is a simple scene manager)
Answer by MacDx · Sep 09, 2017 at 12:05 AM
Maybe something like this
public Image countdownImage;
void Start()
{
StartCoroutine(Countdown());
}
private IEnumerator Countdown()
{
float duration = 3f; // 3 seconds you can change this
//to whatever you want
float normalizedTime = 0;
while(normalizedTime <= 1f)
{
countdownImage.fillAmount = normalizedTime;
normalizedTime += Time.deltaTime / duration;
yield return null;
}
}
Hello. That code is working exactly has I wanted, but there is a problem that probably is simple but I'm overthinking it: how to I show the seconds remaining as text? I can change the text and all that, but can't figure out how to get the time in precise seconds... Thanks for your help.
This answer is still correct and you just need to change how it is expressed a little.
Ins$$anonymous$$d of normalizing the increments and tracking the normalized amount of time, track the raw amount of time and normalize it just before you assign it to fillAmount.
private IEnumerator Countdown()
{
float duration = 3f; // 3 seconds you can change this to
//to whatever you want
float totalTime = 0;
while(totalTime <= duration)
{
countdownImage.fillAmount = totalTime / duration;
totalTime += Time.deltaTime;
var integer = (int)totalTime; /* choose how to quantize this */
/* convert integer to string and assign to text */
yield return null;
}
}
I left to you how you would convert totalTime to the number of remaining seconds. $$anonymous$$athf has a bunch of features that can help with this, like CeilToInt, RoundToInt and FloorToInt.
Answer by Kishotta · Sep 09, 2017 at 01:57 AM
Similar to MacDX's answer:
void DoStuff () {
// Whatever you want to happen when the countdown finishes
}
IEnumerator Countdown (int seconds) {
int counter = seconds;
while (counter > 0) {
yield return new WaitForSeconds (1);
counter--;
}
DoStuff ();
}
This answers a lot but doesn't do what I want more: set the progress bar fill amount. I know I could easily set it with the counter value, but it wouldn't be smooth, and ins$$anonymous$$d snap. How do I smooth it up? I hope you understand what I mean. Thanks.
Your answer
Follow this Question
Related Questions
Making a Timer Out out of 3D Text using C#. 1 Answer
C# simple delay execution without coroutine? 2 Answers
Multiple Cars not working 1 Answer
Countdown Error 1 Answer
Timer going negative...Help 2 Answers