[SOLVED] Coroutine problems

This never outputs “2” in the console? Any reasons why?

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class CollisionHandler : MonoBehaviour {

    public GameObject deathParticle;
    public GameObject player;

    void OnCollisionEnter2D(Collision2D col) {
        if (col.gameObject.tag == "Enemy") {
            Die ();
            StartCoroutine (WaitAWhile());
        }
    }

    void Die() {
        Destroy (player);
        Particles ();
    }

    IEnumerator WaitAWhile() {
        Debug.Log ("1");
        yield return new WaitForSeconds(1);
        Debug.Log ("2");
        SceneManager.LoadScene (0);
    }

    void Particles() {
        Transform point = player.transform;
        for (int i = 0; i < 50; i++) {
            GameObject particle = Instantiate (deathParticle, point.position, point.rotation) as GameObject;
            particle.GetComponent<Rigidbody2D> ().AddForce (new Vector2 (Random.Range(-100, 100), Random.Range(-100, 100)), ForceMode2D.Impulse);
        }
    }

}

Is this script on the player? :slight_smile:

Yes

Okay then, maybe because after 1 second the player is object is destroyed (Player destroyed before 1 second… but you’re waiting 1 second for the second log output*), along with this script… you cannot see it from the Great code beyond :wink:

Thank you so much

Awesome, glad ya got it. :slight_smile: You’re welcome.

How would I handle the player collision from another object, like an empty?

What is it you want to happen / handle on collision? The same thing as above or something new?

I want this to happen:

            Die ();
            StartCoroutine (WaitAWhile());

but I want it to get to the end of the coroutine.

If you don’t have to destroy your player, you could hide it or freeze it & then restart it.
If you really do want to destroy it and make a new one to start the game (to each their own), then you will have to have another script somewhere that loads the new level.
Okay, and one other idea (compromise) is… hide the player for a second (disable input), then Die(); and load the scene over again. Does that make sense at all?

Thank you I got it working.

Cool :slight_smile: