When the scene loads, is there any way to display a count down timer which prevents the game (update function) from running until the count down timer has reached 0? Something like 3 2 1 go … game starts?
I’ve tried this but the game runs and no timer shows up
void Start()
{
StartCoroutine(Countdown(3));
}
IEnumerator Countdown(int seconds)
{
int count = seconds;
while (count > 0) {
// display something...
yield return new WaitForSeconds(1);
count --;
Update ();
}
// count down is finished...
}
void Update () {
//my game stuff
}
Generally, for a case like this, you’ll probably want to use a variable to determine whether or not your game’s in progress, which will mean checking whether a boolean is true every frame (which is incredibly fast, mind you).
This sounds like a bad thing at first, but it can serve alternative purposes as well, such as serving as an additional option for accommodating pausing or removing control for cutscenes.
Anyway, my advice would be to use the coroutine to handle the countdown timer, then when it’s completed, you set a variable true to state that the game’s actively running.
bool isPlaying;
bool countdownActive;
public int countdownTime = 3; // Set to whatever duration of countdown you want applied
void Start()
{
StartCoroutine(Countdown(countdownTime));
}
IEnumerator Countdown(int seconds)
{
countdownActive = true;
for(int i = seconds; i >= 0; i--)
{
if(i > 0) // 3... 2... 1...
{
// Display number or similar representation of countdown
yield return new WaitForSeconds(1.0f);
}
else if(i <= 0) // START!
{
// Display "START!" or "GO!" or similar concept
countdownActive = false;
isPlaying = true;
}
}
return;
}
void Update()
{
if(isPlaying)
{
// Gameplay functionality here
}
if(!countdownActive && Input.GetButtonDown("Pause")) // Define a "Pause" button to accommodate this
{
isPlaying = !isPlaying; // if false, you're paused
}
}
With a setup similar to this, you can pause the game only after gameplay has begun (but not during the countdown itself), but otherwise the gameplay would only take place as long as “isPlaying” is true.