Countdown timer misses a fraction of a second on start up.

This is your basic count down timer. It starts at 3 seconds (I am normalizing the elapsed time) if you look at the log you can see it goes from 2.96 to 2.62 every time. I don’t know what this is happening. help!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TimerScript : MonoBehaviour
{
    [SerializeField] private float totalTime = 3.0f;
    private float scaledValue = 1.0f;
    private float elapsedTime;
    bool timerOn = false;

    void Start()
    {
        scaledValue = 1.0f;
        elapsedTime = totalTime;
        timerOn = true;
    }

    void Update()
    {
        if (timerOn)
        {
            elapsedTime -= 1 * Time.deltaTime;
            scaledValue = elapsedTime / totalTime;
            if (scaledValue < 0.0f){ 
                scaledValue = 0.0f;
                timerOn = false;    
            }
            Debug.Log("scaledValue: " + scaledValue + ", CurrentTime: " + elapsedTime);
        }
    }
}

202162-timess.jpg

From how I understand it, Time.deltaTime measures the amount of time that passed between the previous frame and the current frame. That 1/3rd of a second delay is probably due to the game lagging a bit when everything is first initialized. Your timer should still be accurate; there was just a longer delay while it finished loading things. Here’s something you can try that shouldn’t give you that longer delay:

    void Start()
    {
         StartCoroutine(DelayTest());
    }
    
    IEnumerator DelayTest()
    {
            // Short delay while the game finishes initializing
            yield return new WaitForSeconds(2);
            
            timerOn = true;
            while(timerOn)
            {
                  // Subtract from timer
                  elapsedTime -= 1 * Time.deltaTime;
                  scaledValue = elapsedTime / totalTime;
                  if (scaledValue < 0.0f){ 
                        scaledValue = 0.0f;
                        timerOn = false;    
                   }
                  Debug.Log("scaledValue: " + scaledValue + ", CurrentTime: " + elapsedTime);
                  yield return new WaitForEndOfFrame();
            }
    }