I have a parkour game I am trying to make and I was wondering if anyone had a free timer code that you can reset with pressing a key code, since I don’t know what I am doing (since I started game dev just a month ago).
-thanks
I have a parkour game I am trying to make and I was wondering if anyone had a free timer code that you can reset with pressing a key code, since I don’t know what I am doing (since I started game dev just a month ago).
-thanks
Create a script named Timer and paste this code in it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Timer : MonoBehaviour
{
public float timer = 0;
void Update()
{
//Same as: timer = timer + Time.deltaTime;
timer += Time.deltaTime;
}
public ResetTimer()
{
timer = 0;
}
}
Then you can call the timer float in your UI to show it to you player.
If you want to reset you timer, you just have to call ResetTimer() with a button for exemple.
Tell me if you need more help.
This works so well. but what if I want it to reset it by pressing the R key on a keyboard in real life
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Timer : MonoBehaviour
{
public float timer = 0;
void Update()
{
timer += Time.deltaTime;
// Check if the R key is released
if (Input.GetKeyUp(KeyCode.R))
{
ResetTimer();
}
}
void ResetTimer()
{
timer = 0;
}
}
Input.GetKeyUp()
checks if the R key is released, and if so, it calls the ResetTimer()
method.