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?

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.