Coroutine not Working inside OnTriggerEnter

Viewed 31

I saw some similar questions but literally I can't see where I'm doing wrong. Basicly I need a break before level fail.

public static int point;
public static int health;

void Awake()
{
    point = 0;
    health = 3;
}

void OnTriggerEnter(Collider other)
{
    if(other.gameObject.tag == "coin")
    {
        point ++;

        EventManager.OnCoinPickUp.Invoke();
        Coin.SharedInstance.DisposeOnTrigger(other);
    }
    else if(other.gameObject.tag == "Obstacle")
    {
        health --;

        EventManager.OnPreLevelFail.Invoke();

        if(health == 0)
        {
            StartCoroutine(WaitBeforeFail());
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
        }
    }
}

IEnumerator WaitBeforeFail()
{
    yield return new WaitForSeconds( 1.5f );
    EventManager.OnLevelFail.Invoke();
}

It doesn't work so I would appreciate some help.

1 Answers

What is happening is, you are starting the coroutine, it does, in fact, wait 1.5 seconds, and after that OnLevelFail is invoked. Your problem comes from the fact that the code for changing the scene is not inside the coroutine. So the coroutine is executed but immediately after that the scene changes. If you put the code for the scene inside the coroutine you won't have problems and the scene will change in 1.5 seconds.

You see, starting a coroutine does exactly and only that - starts it. It does not wait before continuing with the following code. The waiting happens inside the coroutine itself.

Related