Question by
LetsBeChillx · Jun 05, 2017 at 12:08 AM ·
c#timerfloatreset
Timer instantly sets to zero
[Coded in C#] I am trying to create two times - one to count down until the game starts and then one to time the round. For some reason, the timers are set instantly to zero when the game starts. Here is the script I have created:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Timers : MonoBehaviour {
public float timer_countdown; //countdown until the game starts; 3 seconds
public float timer_game; //countdown for the game itself; 30 seconds
public Text countdownT; //ui for first timer
public Text countdownG; //ui for second timer
public Text gameDone; //ui to tell player game is over
// Use this for initialization
void Start ()
{
timer_countdown = 3.0f;
timer_game = 30.0f;
countdownG.enabled = false; //round timer is hidden at start
countdownT.enabled = true; //start timer is on at start
gameDone.enabled = false; //game is done text is hidden at start
}
// Update is called once per frame
void Update ()
{
Debug.Log("Timer 1: " + timer_countdown);
Debug.Log("Timer 2: " + timer_game);
while (timer_countdown > 0.0f) //while the timer is not zero...
{
timer_countdown -= Time.deltaTime; //countdown until zero
countdownT.text = timer_countdown.ToString("F3"); //displays timer
}
if (timer_countdown <= 0.0f)
{
timer_countdown = 0.0f; //Ensures the timer is zero for other scripts
while (timer_game > 0.0f)
{
countdownG.enabled = true;
countdownT.enabled = false;
timer_game -= Time.deltaTime;
countdownG.text = timer_game.ToString("F3"); //displays timer
}
}
if (timer_game <= 0.0f)
{
timer_game = 0.0f; //Ensures timer is zero for other scripts
//disable both timers
countdownG.enabled = false;
countdownT.enabled = false;
gameDone.enabled = true;
//Make a call to the scoring screen and stuff here
}
}
}
In the console, it says the timers are set to their beginning time for a single frame then set to zero the second and stay zero. Any help? Thanks to any and all.
Comment
Best Answer
Answer by Sergio7888 · Jun 05, 2017 at 06:52 PM
Update is called every frame for this reason sometimes a while need be replaced with a if or be removed.
while (timer_game > 0.0f)
{
countdownG.enabled = true;
countdownT.enabled = false;
timer_game -= Time.deltaTime;
countdownG.text = timer_game.ToString("F3"); //displays timer
}
Will became:
if (timer_game > 0.0f)
{
countdownG.enabled = true;
countdownT.enabled = false;
timer_game -= Time.deltaTime;
countdownG.text = timer_game.ToString("F3"); //displays timer
}
in your case you need do this for every while in your Update