C# WaitForSeconds doesn't seem to work ??

Hello everyone,

I’m trying to write a script that when the player looses, an animation is displayed (it’s an explosion) then the function lose() is called. The function lose() simply waits for the animation to finished, then pause the game and tells the GUI to show the “Game Over” screen.

Here is my code :

public void Lose()
{
            print("Begin Lose() " + Time.time);
            StartCoroutine(Wait(3.0f));
            print("End Lose() " + Time.time);
            Time.timeScale = 0;
	guiMode = "Lose";
}

private IEnumerator Wait(float waitTime)
{
            print("Begin wait() " + Time.time);
	yield return new  WaitForSeconds(waitTime);
            print("End wait() " + Time.time);	
}

The log is :
Begin Lose() 4.86
Begin wait() 4.86
End Lose() 4.86

And that’s all !

It’s as if the Wait() function is “paused”, but the Lose() function goes on nonetheless and, because of the Time.timeScale = 0, the execution of the Wait() function can’t be finished and everything freezes.

Why the Lose() function doesn’t stop 3 seconds when the Wait() function is called ??

Thanks !

Anything you want to be delayed has to be within the IEnumerator. So, your observation is correct and this is what happens.

  1. Lose Function starts
  2. Wait Function Begins (Delaying everything after the WaitForSeconds in the coroutine)
  3. Lose Function stops time
  4. Wait Function is halted due to the fact that time is no longer advancing
  5. Lose Function exits

To fix this, place you change to Time.timeScale within the Wait() function.

Just to reiterate starting a coroutine does not delay any aspects of the function it is called within, only behaviors within the coroutine will be delayed. Here is how the code has to be written for this to work as intended:

public void Lose()
	{
		print("Begin Lose() " + Time.time);
		StartCoroutine(Wait(3.0f));
		// This print line will not have a
		// Delay.  It is called immediately
		// following the start of the coroutine
		print("End Lose() " + Time.time);

	}

	private IEnumerator Wait(float waitTime)
	{
		print("Begin wait() " + Time.time);
		yield return new WaitForSeconds(waitTime);
		// Change to the timescale must be called here
		// to prevent this coroutine from halting
		Time.timeScale = 0;
		guiMode = "Lose";
		print("End wait() " + Time.time);
	}

void Start ()
{
StartCoroutine(WaitForPlay(2.0f));
}

IEnumerator WaitForPlay(float waitTime)
{
yield return new WaitForSeconds(waitTime);
print(“play”);
}