I used the C# Stopwatch Class in Unity, but it returns only 00:00:00
10,584
Solution 1
You are re-creating the stopwatch when calling update. You can initialize the stopwatch on forehand in the "constructor".
public Stopwatch zeit = new StopWatch();
void Update () {
if (Input.GetKeyDown ("tab")) {
zeit.Start();
}
if (Input.GetKeyDown ("space")){
TimeSpan ts = zeit.Elapsed;
zeit.Stop ();
print(ts);
zeit.Reset ();
}
}
Solution 2
I think the problem is you always create a new object and set it into zeit variable each Update function is raised.
So, you must create that object only one time.
public Stopwatch zeit = new Stopwatch();
void Update () {
if (Input.GetKeyDown ("tab")) {
zeit.Start();
}
if (Input.GetKeyDown ("space")){
TimeSpan ts = zeit.Elapsed;
zeit.Stop ();
print(ts);
zeit.Reset ();
}
}
Solution 3
You have to move your instantiation of Stopwatch
outside of Update
. Currently you are recreating your stopwatch every frame.
So move zeit = new Stopwatch();
outside of Update
private readonly Stopwatch zeit;
void Start()
{
zeit = new Stopwatch();
}
void Update()
{
//...
}
Solution 4
You create new Stopwatch each Update method:
void Update () {
zeit = new Stopwatch();
Don't do that, instead, try this approach:
private readonly Stopwatch _zeit = new Stopwatch();
void Update ()
{
if (Input.GetKeyDown ("tab"))
{
_zeit.Restart();
}
if (Input.GetKeyDown ("space")
{
print(_zeit.Elapsed);
}
}
Author by
Fred
Updated on July 31, 2022Comments
-
Fred almost 2 years
I want to measure and return the time that passes between the time a user presses the Tab & the Space Button. Unfortunately my Code only returns 00:00:00. This is my code so far.
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Threading; using System; using System.Diagnostics; using Debug=UnityEngine.Debug; public class timer : MonoBehaviour { public Stopwatch zeit; void Update () { zeit = new Stopwatch(); if (Input.GetKeyDown ("tab")) { zeit.Start(); } if (Input.GetKeyDown ("space")){ TimeSpan ts = zeit.Elapsed; zeit.Stop (); print(ts); zeit.Reset (); } } }
-
UnholySheep over 6 yearsYou are creating a new
Stopwatch
every single frame. You want to movezeit = new Stopwatch();
outside of theUpdate
(e.g. inStart
?)
-
-
Izukani over 6 yearsIt is not necessary to Stop to get the Elapsed time.