Problem with coroutines in 2D game C#

I am using as coroutine so that something happens 2 seconds after another few things.

IEnumerator MyMethod()
{
Debug.Log ("Dead");
Destroy (PlayerSprite);
yield return new WaitForSeconds(2.0f);
Application.Loadlevel("Level 1")
Debug.Log("Loading level?");
}

Want I want this to do is send ‘dead’ and such, wait 2 seconds, and then reload the level with Application.LoadLevel. I call the coroutine later like this:

StartCoroutine(MyMethod());

The Debug.Log(“Dead”); is sent and everything before, but nothing after the 2 seconds happens, including the second Debug.Log! Anyone know what part I’m phrasing incorrectly? - JS

I would assume because it’s loading a new level, all the code is stopping completely.

1 Like

this is mostly like the situation here, move the “Loading Level” log above Application.Loadlevel

1 Like

I would be surprised if this is the case, Since there is no yield statement after the call to LoadLevel and I don’t think unity would hijack execution from you without any yield specified.

I would more bet that the script or or the gameObject the script is on is PlayerSprite which you destroy prior to the wait.

I’m guessing no level load occurs?

As bdev says, if you destroy an object that a coroutine is running on, it also deletes the coroutine and it will never finish.

1 Like

probably important to note that unity won’t ‘stop’ the coroutine immediately with the call to delete ( as it’ll never just eject your code ), rather if you yield return after the object was destroyed within the coroutine, control will not be returned to the coroutine.

The answer, as it turns out, was that part of the coroutine involved destroying the player, the gameobject the script itself was attached to. Once it was destroyed, the coroutine couldn’t continue… thanks for all of your help!

1 Like