How to wait 5 seconds after a trigger is activated?

I try to wait five seconds after the trigger is executed, and after five seconds I want to move on to the next scene. The problem is that after the trigger fires, it automatically proceeds to the next scene.

What i tried

using UnityEngine;
using System.Collections;

public class DestroyerScript : MonoBehaviour {


IEnumerator WaitAndDie()
{
    yield return new WaitForSeconds(5);

}
void Update()
{

        StartCoroutine(WaitAndDie());         

}
void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Player") 
    {
        Update();     
        Application.LoadLevel("GameOverScene");
        return;
    }

}
}

I also tried

using UnityEngine;
using System.Collections;

public class DestroyerScript : MonoBehaviour {


IEnumerator WaitAndDie()
{
    yield return new WaitForSeconds(5);

}

void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Player") 
    {
        StartCoroutine(WaitAndDie());         
        Application.LoadLevel("GameOverScene");
        return;
    }

}
}
+4
source share
2 answers

This should work

using UnityEngine;
using System.Collections;

public class DestroyerScript : MonoBehaviour {


bool dead;

IEnumerator OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Player") 
    {
        yield return new WaitForSeconds(5);
        Application.LoadLevel("GameOverScene");
        dead = true;
        return dead;

    }

}
}
+2
source

Call Application.LoadLevelonly after yield return:).

IEnumerator WaitAndDie()
{
    yield return new WaitForSeconds(5);
    Application.LoadLevel("GameOverScene");
}

void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Player") 
    {
        StartCoroutine(WaitAndDie());         
        return;
    }

}
}
+5
source

All Articles