- Home /
Made a real time timer but it updates too sporadically/weirdly
So, made a simple mobile game that has a real time timer. It will show how much time elapsed (to the second) from the moment you started a session. You can be running a session even if the app is closed or the phone is asleep.
The first version of the code would save the session start time. Then it would use a coroutine to add up the seconds in integers as they passed. (The clock starts at 0 at the beginning of the session.)
The problem with this is that the coroutine would stop when the player's device is put to sleep. So instead of calculating it that way, I decided the clock would display the time elapsed between the current time and start time for each second, again using a coroutine.
Now the issue is that the timer displays weirdly. The seconds seem(?) to go faster than they're supposed to.
Here is the code:
public class Timer : MonoBehaviour
{
public TMP_Text timerText;
public DateTimeValue timeStarted;
public IEnumerator RunTimer()
{
while (true)
{
var rightNow = DateTime.Now;
TimeSpan timeElapsed = rightNow - timeStarted.value;
DisplayTimer(timeElapsed);
yield return new WaitForSeconds(1f);
}
}
public void DisplayTimer(TimeSpan timeElapsed)
{
timerText.text =
$"{timeElapsed.Days} days\n" +
$"{timeElapsed.Hours} hours\n" +
$"{timeElapsed.Minutes} minutes\n" +
$"{timeElapsed.Seconds} seconds\n";
}
}
Appreciate any help on how to get the display to consistently update the current number of seconds elapsed, instead of have a jerky and inconsistent output.