- Home /
Why is my Timer like this?
I know my code may be messy cause im still a beginner, gimme a break. I dont understand how the do while loop worked this way. I wanted it to count down from 2 to 0, as assigned in "countDownTime". If i made it while(countDownTime >= 0), it would actually start the countdown from 0. I dont understand the logic of it not counting down from 2, when I assigned it to countdown while (countDownTime > = 0), and it wouldnt even stop at 0,; it would keep going negative.
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using UnityEngine.UI; using TMPro; public class DuelGame : MonoBehaviour { [SerializeField] TextMeshProUGUI p1ScoreBox; [SerializeField] TextMeshProUGUI p2ScoreBox; [SerializeField] TextMeshProUGUI timer1; [SerializeField] TextMeshProUGUI timer2; [SerializeField] float countDownTime = 2f; float time; bool hasStarted = false; bool timerStart = false; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Space) && !hasStarted) { hasStarted = true; StartGame(); } DisplayTime(); } void DisplayTime() { if (timerStart) { do { countDownTime -= Time.deltaTime; } while (countDownTime >= 2); timer2.text = Math.Round(countDownTime, 2).ToString(); } }
You need to add 4 spaces before every lines in order to get the code formated
Answer by ErikH2000 · Sep 27, 2019 at 11:57 PM
You really should figure out the code formatting so your code doesn't jumble together in one line.
Your do...while
loop is always going to subtract some amount of time from your countdown. You could try a while
loop instead, which checks the expression at the beginning of the loop (instead of the end, like you have it). If the expression isn't true, then it won't enter the loop and subtract from your countdown.
while (countDownTime >= 2) {
countDownTime -= Time.deltaTime;
}
There is another way to check for time that I like to use, because you don't need to update variables:
public class DuelGame : MonoBehaviour {
const float COUNTDOWN_DURATION = 2f;
float countdownStartTime;
bool hasStarted = false;
void Update() {
if (Input.GetKeyDown(KeyCode.Space) && !hasStarted) {
hasStarted = true;
countdownStartTime = Time.time;
StartGame();
}
DisplayTime();
}
void DisplayTime() {
if (hasStarted) {
float elapsedSinceStarted = Time.time - countdownStartTime;
if (elapsedSinceStarted <= COUNTDOWN_DURATION) {
timer2.text = Math.Round(COUNTDOWN_DURATION - elapsedSinceStarted, 2).ToString();
}
}
}
}
Your answer
Follow this Question
Related Questions
How do you make a time bomb beeper 0 Answers
[Closed]Unity crash, while/for loop 3 Answers
Can I use a while() in the function OnDrawGizmos() ? 1 Answer
While loop crashes unity 1 Answer
How to have a Count Down Timer carry over to a new level? 2 Answers