- Home /
Question by
Antao98 · Feb 20, 2018 at 03:52 PM ·
timertimer countdowncondition
Start countdown timer with condition
So I've been trying to make a timer start when a condition is met, but the timer I have is using the time since the scene started, so even if I use it inside a statement, the timer will have already begun. This is my code, already displaying in the UI, and with the condition.
public Text timerText;
float time;
float remainingTime;
[HideInInspector]
public bool timesUp;
bool startTest = false;
// Use this for initialization
void Start () {
timesUp = false;
time = Time.time;
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown (KeyCode.Space))
{
startTest = true;
}
if(startTest == true)
{
StartTimer ();
}
}
void StartTimer()
{
time = Time.time;
remainingTime = 60f - time;
timerText.text = remainingTime.ToString ("F0");
if(remainingTime <= 0)
{
timesUp = true;
timerText.text = "0";
}
}
Comment
Ins$$anonymous$$d of time = Time.time
manually do it like:
time -= 1 * Time.deltaTime;
Best Answer
Answer by Hellium · Feb 20, 2018 at 04:03 PM
public Text timerText;
float time;
float remainingTime;
[HideInInspector]
public bool timesUp;
bool timerIsRunning = false;
bool timerIsUp = false;
// Use this for initialization
void Start ()
{
timesUp = false;
time = Time.time;
}
// Update is called once per frame
void Update ()
{
if(timerIsRunning)
{
UpdateTimer ();
}
else if(!timesUp && Input.GetKeyDown (KeyCode.Space))
{
StartTimer();
}
}
void StartTimer()
{
time = Time.time;
timerIsRunning = true ;
}
void UpdateTimer()
{
remainingTime = time + 60f - Time.time;
timerText.text = remainingTime.ToString ("F0");
if(remainingTime <= 0)
{
timesUp = true;
timerText.text = "0";
timerIsRunning = false ;
}
}