- Home /
While loop timer stops when button is pressed.
Good Evening, I am trying to create a script that will countdown from 5. Before the countdown, the script will wait a random number of seconds before saying "Go!". During this countdown, if the user presses the key "x" before the timer has finished counting down then the user wins. However, if the user does not press x before the countdown completes, the computer wins. I tried doing this in a while loop but it didn't work. The variable seconds will almost immediately drop to below 0 setting cpuWin to true.
var cpuWin : boolean = false;
var playerWin : boolean = false;
var seconds : float = 5.0;
function Start () {
yield WaitForSeconds(Random.Range(1,10));
Debug.Log("Go!");
while(seconds > 0) {
if(Input.GetKey("x")) {
playerWin = true;
Debug.Log("You win!");
break;
}
seconds -= Time.deltaTime;
if(seconds <= 0) {
cpuWin = true;
Debug.Log("You lose!");
break;
}
}
//Once out of the loop do other stuff.
}
Sorry if im missing something here. Im getting back into programming before I go back to school and my logic and coding is very rough. Am I at least headed in the right direction? Or is there an easier way to do this?
Answer by AdamScura · Feb 11, 2014 at 03:20 AM
What you're missing is how Unity handles the main game loop.
You don't make the main loop yourself in a script - Unity handles the main loop for you automatically.
Put your startup code in the "Start" function. Put the code that executes every frame into the "Update" function. Unity will automatically call these functions on every active script in your scene at the appropriate time.
Here is a great info-graphic that shows the life-cycle for a Unity script. You can implement any of those functions to hook your code into the main loop and it will be executed automatically.
It probably wouldn't hurt to read through the unity manual as well.
A delay can be done in unity by creating a Coroutine.
Thanks for that infographic! It should come in handy. It looks like im going to need some more training before I really begin doing things myself. I'm going to go through some of the tutorials since I dont understand how Unity works quite yet. Im used to typing it all myself, the fact that Unity does it for you is great, I just have to figure out how to get it to work for me. Thanks again!
Your answer

Follow this Question
Related Questions
Unity While Loop Freeze 2 Answers
Audio trigger by key press - problems 1 Answer
Problems with GetKeyUp generating text outside Unity 1 Answer
Input.GetKey not working 1 Answer
Is SimpleMove() framerate-independent under the hood? 1 Answer