- Home /
Can someone help me use GetKeyDown functions with this script. I've tried so many combinations
This script works fine using UI "Buttons" However, I am looking to use GetKeyDown & GetKeyUp functions to start and stop the timer. It seems logical to do but I just can't find a solution using Input.GetKeyDown functions.
float val;
bool timerActive;
public Text timerText;
// Start is called before the first frame update
void Start()
{
val = 0;
timerActive = false;
}
void Update()
{
if (timerActive)
{
val += Time.deltaTime;
}
double b = System.Math.Round(val, 2);
timerText.text = b.ToString("F2");
}
public void startbutton()
{
timerActive = true;
}
public void stopbutton()
{
timerActive = false;
}
Answer by stachojakub · Jun 02 at 06:07 PM
Hi @Var1g ! It would be enough just to add this snippet of code at the beginning of the Update function.
if (Input.GetKeyDown(KeyCode.Q))
timerActive = true;
if (Input.GetKeyDown(KeyCode.E))
timerActive = false;
And you can put your own keys there instead my Q and E
Hope it helps!
Thank you. It's exactly what I am looking for. How would I store this number and use it as a time to beat. Like a fastest lap per se ?
Put this before the Start() function:
float bestTime;
bool firstLap = true;
And this into the Update() function:
if (firstLap == true)
{
bestTime = val;
firstLap = false;
}
else if (val < bestTime)
{
bestTime = val;
}
Could you clarify more what are you trying to do? What number do you mean?
Yeh sorry. Questions always seem much clearer for the person asking them. Thanks for getting back to me.
My game is time based. Where the shortest time to complete the level is the time to beat. I want to take that level time and display it as the Best Time. If that makes sense? If you want the snippet of code. Let me know. thanks in advance.
I would add new function with the newTime parameter. It will be sufficient to call that function when you set the new time of the lap. Here is whole code:
float val;
float bestTime;
bool timerActive;
public Text timerText;
// Start is called before the first frame update
void Start()
{
val = 0;
timerActive = false;
bestTime = float.MaxValue;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Q))
timerActive = true;
if (Input.GetKeyDown(KeyCode.E))
timerActive = false;
if (timerActive)
{
val += Time.deltaTime;
}
double b = System.Math.Round(val, 2);
timerText.text = b.ToString("F2");
}
public void SetNewTime(float newTime)
{
if (newTime < bestTime)
bestTime = newTime;
}