- Home /
Question by
TheIncognito · Oct 12, 2013 at 09:44 PM ·
c#
How to reset a timer
I am currently using Time.time to make a countdown timer (if you don't beat the game in x amount of time, you lose) but the issue is that when using the timer code, you cant reset Time.time without hard reloading the game,
using UnityEngine;
using System.Collections;
public class Timer : MonoBehaviour {
public bool timesUp = false;
void OnGUI () {
GUI.Box (new Rect(0, 0, Screen.width/2, 20), Time.time + "/ 75");
}
// Update is called once per frame
void Update () {
if(Time.time >= 75)
{
timesUp = true;
}
if(timesUp == true)
{
Application.LoadLevel (7);
}
}
}
Comment
Best Answer
Answer by v42 · Oct 12, 2013 at 10:41 PM
Why don't you use deltatime instead? This way, you will have full control about how much time have elapsed since you set. After that, you can reset it by just setting it back to zero.
Example:
float elapsedTime = 0;
Then
elapsedTime += Time.deltaTime;
if(elapsedTime >= 75) {
timesUp = true;
Application.LoadLevel(7);
elapsedTime = 0;
}
Answer by meat5000 · Oct 12, 2013 at 10:00 PM
float timer = 0.0;
float countTime = 75.0;
void Update()
{
timer += Time.deltaTime;
if(timer >= countTime)
{
//timer = 0.0;
}
}
Answer by DylanW · Oct 13, 2013 at 03:28 AM
public float max_time = 75.0f;
public float time = 0.0f;
uint time_mul = 0;
void Update()
{
// Calculate time.
time = (Time.time - (max_time * time_mul));
Debug.Log(time);
// Time is up.
if(time >= max_time) {
// Do whatever:
Application.LoadLevel(7);
// Reset time.
time = 0.0f;
time_mul ++;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613115827im_/https://answers.unity.com/themes/thub/images/avi.jpg)