- Home /
Hello, I'm wondering how I can make this little timer accumulate with every press. Currently it resets each time the key is pressed. I want it to continue counting
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Timer : MonoBehaviour { public float timeStart;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
timeStart = Time.time;
}
if (Input.GetKey(KeyCode.Space) && Time.time - timeStart > 0f)
{
Debug.Log((Time.time - timeStart).ToString("F2"));
}
}
}
Comment
Best Answer
Answer by rh_galaxy · May 31 at 10:42 AM
You reset timeStart every time you press space and the next if-statement will never be true because Time.time - timeStart
is 0.
This may be what you want:
bool bFirstTime = true;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && bFirstTime)
{
timeStart = Time.time;
bFirstTime = false;
}
if (Input.GetKey(KeyCode.Space) && Time.time - timeStart > 0f)
{
Debug.Log((Time.time - timeStart).ToString("F2"));
}
}
Your answer
Follow this Question
Related Questions
timer starts in the menu scene 1 Answer
Convert this string formatting from C# to JS 1 Answer
Start timer with trigger 1 Answer
I want particle to emit for one second after my mouseclick 1 Answer