1
\$\begingroup\$

Hello's I was looking for a way to do a countdown timer in unity and stumbled across this solution :

public float timeRemaining = 10;

private void Update()
{
    if (timeRemaining > 0)
    {
        timeRemaining -= Time.deltaTime;
    }
    else
    {
        WinGame();
    }
}

Which at first seemed pretty elegant and easy to use, however, I was thinking about it, and wouldn't this be inconsistent for players with different FPS?

For example, if the player has 60 FPS vs 30 fps it would take longer for the player having 60 FPS to reach 0 on time remaining.

\$\endgroup\$
1
  • \$\begingroup\$ By using deltaTime, the timer should be independant of the amount of FPS. deltaTime is the time between the current and last frame, meaning on 60fps the time is smaller than on 30fps. So for people with 60fps the timer updates 60 times with a small amount, for 30fps the timer updates 30 times with a bigger (x2) amount. So for both users, the timer depletes in the same amount of time, but the steps per frame are just different in size. \$\endgroup\$
    – D.Kallan
    Dec 31, 2020 at 6:56

2 Answers 2

5
\$\begingroup\$

By using deltaTime, the timer is independant of the amount of FPS.

deltaTime is the time between the current and last frame, meaning on 60 fps the delta time is smaller than on 30 fps. So for people with 60 fps the timer updates 60 times with a small amount, for 30 fps the timer updates 30 times with a bigger amount (in this case double).

So for both users, the timer depletes in the same amount of time, but the steps per frame are just different in size.

\$\endgroup\$
1
\$\begingroup\$

You can also use Coroutines and InvokeReapeating. The advantage is that you can run many of them in one script and your Update function doesn't get cluttered.

example with InvokeReapeating:

public int theCount =300;

void Start()
{
    InvokeRepeating("doCoundDown", 1, 1);  //fires the function every second
}

public void doCoundDown()
{
    if (theCount>=0) {
        theCount--;
    }
    else {
        // timer is finished...
        CancelInvoke();
    }
}

example with Coroutine:

void Start()
{
    StartCoroutine(doCoundDown());  //fires coroutine
}

public IEnumerator doCoundDown()
{
    for (let i = 300; i > 0; i--) {
        yield return new WaitForSeconds(1);
    }
      
    // timer is finished...
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .