Unity2D: Delay before SceneManager loads the next scene

Viewed 1526

I know this has been asked before, but i am not being able to implement it correctly. When my player collides with certain objects tagged with "Death" or "Next Level", they load their respective scenes, but i want a delay before SceneManager loads the next scene

private void OnTriggerEnter2D(Collider2D other)

if (other.gameObject.CompareTag("Next"))
 
// I want about a 1 second delay here//
        
{ SceneManager.LoadScene("Level 2"); }

hope you guys can help me out, help is much appreciated.

1 Answers

Sounds like you want to wait a few seconds before executing a piece of code. This is normally not possible, because Unity waits for the code to finish executing before it draws the next frame.

What you want instead is some code that can wait a certain number of frames before continuing. For this, Coroutines are used.

So when the player is hit, you want to start a coroutine that loads the next scene after waiting 1 second.

Define the coroutine like this:

IEnumerator NextLevelAfterWait() {
    yield return new WaitForSeconds(1.0f);
    
    SceneManager.LoadScene("Level 2");
}

And then you call the coroutine at the right time like so:

private void OnTriggerEnter2D(Collider2D other) {
    if (other.gameObject.CompareTag("Next"))
        StartCoroutine(NextLevelAfterWait()); 
}
Related