- Home /
Question by
DieEnte · May 25, 2014 at 08:52 PM ·
c#waitforsecondsongui
Use WaitForSecounds in OnGUI()
I would like to make a countdown from 3 when you hit "resume" in the menue. So that you have 3 seconds to focus before the game continues. But the WaitForSeconds somehow doesn't work and it all gets execute at the same time. Heres my code;
void OnGUI () {
if (resume == true) {
//TODO Countdown erstellen
for (int i = 3; i > 0; i--){
resumeCountdown = true;
if(resumeCountdown == true){
GUI.Box(new Rect(0, 0, topW, topH), "" + i);
}
StartCoroutine(waitOneSecound());
resumeCountdown = false;
}
resume = false;
menubutton = true;
//TODO Besserer Weg um das Spiel wieder zu starten
Time.timeScale = 1;
}
}
IEnumerator waitOneSecound(){
yield return new WaitForSeconds (1);
}
Comment
Wiki
Answer by TKS_Keeper · May 25, 2014 at 11:30 PM
Your problem is a pretty easy one to make, and it at it heart lies a misgiving about how the "yield" works in Unity.
The culprit:
yield return new WaitForSeconds (1); } This will cause the unity engine to return from the waitOneSecound function to it's parent function at the yield marker, wait one second, and then CONTINUE execution after the yield (which in this case does nothing). What you want is probably something like this: public class CountDownGUIWidget: Monobehavior{IEnumerator waitOneSecound(){
private int countdownRemaining;
void OnGUI () { if(countdownRemaining>0){ GUI.Box(new Rect(0, 0, topW, topH), "" + countdownRemaining); } }
void startCountdown(int countdownTimeInSeconds){ countdownRemaining = countdownTimeInSeconds; StartCoroutine(startCountdownTimer()); }
/// starts the timer, and updates it once a second IEnumerator startCountdownTimer(){ ++countdownRemaining; //one time increase of the countdown because the loop will lower it immediately //do the countdown! while((--countdownRemaining) > 0){ yield return new WaitForSeconds (1); } endCountdown(); }
void endCountdown(){ countdownRemaining = 0;//just in case, set countdownRemaining to 0 resume = false; menubutton = true; //TODO Besserer Weg um das Spiel wieder zu starten Time.timeScale = 1;
} }
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to make OnGUI Texture able to be clicked 1 Answer
I press ESC once, Unity thinks I've pressed it many times... 2 Answers
c# waitforsecconds 2 Answers