What is wrong when calling this WaitForSeconds in a Coroutine?

I can’t seem to figure out what I’m doing wrong.

I’m calling
StartCoroutine (WaitToDestroy (2));

And then

	IEnumerator WaitToDestroy(float it)
	{
		print ("time1" + Time.time);

		yield return new WaitForSeconds (it);

		print ("time2" + Time.time);

		Destroy (this.gameObject);

		yield return null;
	}

And time 1 is the only one being printed :S

What i would do is have a method that i would INVOKE after 2 seconds, basically this will delay the execution for 2 seconds, then the function gets executed. If you need help leave a comment.

There are basically 3 reasons why only time1 is printed:

  • The object of script component is destroyed before the wait time is over. This will terminated the coroutine immediately.
  • You set Time.timeScale to 0 which will freeze all time based operations which includes WaitForSeconds
  • You called StopAllCoroutines in a script which might have terminated the coroutine before it was finished.

Like Raresh said you might want to simply use Invoke or just Destroy since Destroy allows you to pass a delay:

Destroy(gameObject, 2);

However Time.timeScale should not be set to 0.