Search Unity

Unity Timer

Discussion in 'Assets and Asset Store' started by SimpleUnityTutorials, Apr 7, 2023.

  1. SimpleUnityTutorials

    SimpleUnityTutorials

    Joined:
    Apr 5, 2023
    Posts:
    4
    If you want advanced timer in unity
    Just watch this video



    It has only one script and so simple
     
  2. elmar1028

    elmar1028

    Joined:
    Nov 21, 2013
    Posts:
    2,359
    Thanks for creating tutorials like these.

    But have you considered this?

    Code (CSharp):
    1. private float elapsedTimeSeconds = 0f;
    2.  
    3. private void Update() {
    4.     elapsedTimeSeconds += Time.deltaTime;
    5.     var timeSpan = TimeSpan.FromSeconds(elapsedTimeSeconds);
    6.     var formattedTimeStr = timeSpan.ToString(@"hh\:mm\:ss\:fff");
    7.  
    8.     // assign `formattedTimeStr` to a UI element text
    9. }
    Time.deltaTime returns the number of seconds elapsed between frames (docs). Update() call in Unity components runs every frame (docs). That way you can figure out how much time has passed.

    It's not perfect as the code is not taking framerate into account. I think it could be better, but it's simpler.

    If you want to make a countdown timer you simply deduct Time.deltaTime and check if the time is <= 0.
     
  3. SimpleUnityTutorials

    SimpleUnityTutorials

    Joined:
    Apr 5, 2023
    Posts:
    4
    Hi my friend
    Your solution is good
    But I have milliseconds also