Unity3D countdown timer too fast error

facebooktwittergoogle_plusredditpinterestlinkedintumblrmail

Unity3D countdown timer counts too fast error:

If you have coded a countdown timer, but upon multiple uses you’ve discovered it counts down faster and faster, chances are you are starting multiple identical coroutines. We’ll look at a small example to figure out how this issue might be solved.

First we’ll need to declare variables and ensure your countdown timer is a coroutine, plus a basic GUI so we can see what is going on. The following JavaScript code will replicate the error we are talking about:

 

We’ll presume that your coroutine is started/called whenever you need the countdown to take place (in this case pressing the START button).

Now the issue is, if you are calling these timer coroutines more than once, you’ll need to call a StopCoroutine(<functionname>) for each StartCoroutine(<functionname>) you call. Failing to do this will have a cumulative error effect, causing the timer to count down faster than it should. A good way to track if you have one running is to set a boolean variable whenever you start/stop one.

So in this case, we’ll call StopCoroutine(<functionname>) with:

 

 

If there are error checks, if-else blocks, GUI events or other changes that will stop, reset or hide the timer, you’ll need to be sure to add a StopCoroutine(<functionname>) call in each of those code blocks.

The final working code is below:

One Comment

  1. Pingback: Article: Unity3D timer counts too fast error | VISUALS+CODE

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">