Trouble with WaitForSeconds

I made a small space invader style game, and I want my ship to finish exploding before I load the endgame screen, so I’m trying to use WaitForSeconds to get it to pause.

The code that calls my IEnumerator

void OnTriggerEnter2D (Collider2D collider){
        Projectile missile = collider.gameObject.GetComponent<Projectile> ();
        if (missile) {
            health -= missile.GetDamage();
            Debug.Log(health);
            missile.Hit();
            if (health <= 0){
                Destroy(gameObject);
                StartCoroutine (Explode ());
            }
        }
    }

My IEnumerator function Explode()

IEnumerator Explode(){
        ParticleSystem Explosion = Instantiate (explode, transform.position, Quaternion.identity) as ParticleSystem;
        AudioSource.PlayClipAtPoint (boomSound, transform.position, .5f);
        Debug.Log ("Exploded");
        print (Time.time);
        yield return new WaitForSeconds (.2f);
        print (Time.time);
        Debug.Log ("Loading...");
        Application.LoadLevel ("Win Screen");
    }

that code yields the following in my Console

Exploded
UnityEngine.Debug:Log(Object)
c__Iterator0:MoveNext() (at Assets/Scripts/PlayerController.cs:47)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
PlayerController:OnTriggerEnter2D(Collider2D) (at Assets/Scripts/PlayerController.cs:120)

5.86
UnityEngine.MonoBehaviour:print(Object)
c__Iterator0:MoveNext() (at Assets/Scripts/PlayerController.cs:48)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
PlayerController:OnTriggerEnter2D(Collider2D) (at Assets/Scripts/PlayerController.cs:120)

And no matter how long I wait, I never get to the second Time.time print. Can anyone see what is wrong? Am I not allowed to Start a Coroutine from OnTriggerEnter2D?

EDIT: well, actually, I already know I can start one since the function gets called and the explosion part happens, but the waiting and level loading don’t.

You’re destroying the current object (the object running this script) and then trying to run a coroutine from this script. Even if by some trickery of garbage cleanup this is allowed in this current frame, when you tell it to wait a fifth of a second the instance of the coroutine isn’t going to exist anymore.

Anyways, if the current object is not set to Don’t Destroy On Load, then it’ll be destroyed automatically when the new level is loaded. If it is set to Don’t Destroy On Load, then you can destroy it after loading the level- as your final act in the coroutine.

1 Like

Thanks for the reply!

So how come I still get to instantiate the Explosion after I have destroyed the gameObject?

And, if I take out Destroy(gameObject) then it should still destroy itself when my new level loads, and the coroutine should run normally?

EDIT: taking out the destroy (gameObject) made the waitforseconds coroutine work, but I also need to find away to make the sprite disappear without destroying the object.