timer stopwatch

hi i was just wandering how i would get an accurate timer to seconds?

it has to have milliseconds seconds minutes and hours, but time.time cant be used as it needs to reset sometimes back to zero. invokerepeating is good for it if i dont use milliseconds,

1 Like

using System.Diagnostics;

public Stopwatch timer;

//ctr
timer = new StopWatch();

timer.Start();

// delay

timer.End();

use timer.Elapsed ( its a TimeSpan instance)

if you use debug in the same class it will interfere with the Debug in class in c# so just use it a class you do not Debug :slight_smile:

If anybody else comes across this and doesn’t want to use the diagnostics one, here’s a custom class I wrote.

//Written by Daniel Keele - 6/6/2019
 using System;
 using UnityEngine;
 
 public class Stopwatch : MonoBehaviour
 {
     private float elapsedRunningTime = 0f;
     private float runningStartTime = 0f;
     private float pauseStartTime = 0f;
     private float elapsedPausedTime = 0f;
     private float totalElapsedPausedTime = 0f;
     private bool running = false;
     private bool paused = false;
     
     void Update()
     {
         if (running)
         {
             elapsedRunningTime = Time.time - runningStartTime - totalElapsedPausedTime;
         }
         else if (paused)
         {
             elapsedPausedTime = Time.time - pauseStartTime;
         }
     }
 
     public void Begin()
     {
         if (!running && !paused)
         {
             runningStartTime = Time.time;
             running = true;
         }
     }
 
     public void Pause()
     {
         if (running && !paused)
         {
             running = false;
             pauseStartTime = Time.time;
             paused = true;
         }
     }
 
     public void Unpause()
     {
         if (!running && paused)
         {
             totalElapsedPausedTime += elapsedPausedTime;
             running = true;
             paused = false;
         }
     }
 
     public void Reset()
     {
         elapsedRunningTime = 0f;
         runningStartTime = 0f;
         pauseStartTime = 0f;
         elapsedPausedTime = 0f;
         totalElapsedPausedTime = 0f;
         running = false;
         paused = false;
     }
 
     public int GetMinutes()
     {
         return (int)(elapsedRunningTime / 60f);
     }
 
     public int GetSeconds()
     {
         return (int)(elapsedRunningTime);
     }
 
     public float GetMilliseconds()
     {
         return (float)(elapsedRunningTime - System.Math.Truncate(elapsedRunningTime));
     }

	 public float GetRawElapsedTime()
     {
         return elapsedRunningTime;
     }
 }