End level after x seconds

Hey Fellas,

I have this but it does not seem to work:

using UnityEngine;
using System.Collections;

public class FinishLevel : MonoBehaviour {
	public string LevelName;

	public void OnTriggerEnter2D (Collider2D other)
	{
		if (other.tag == "Player") {
			StartCoroutine("MyMethod");
			Application.LoadLevel (LevelName);
		}
	}

	IEnumerator MyMethod() {
		yield return new WaitForSeconds(5);
	}
}

The Application.LoadLevel() call should be placed inside of the coroutine, and will be called by the coroutine after the coroutine has waited the alotted amount of time.

Try:

    IEnumerator MyMethod() {
        yield return new WaitForSeconds(5);
        Application.LoadLevel(0);

        yield return null;
    }

Otherwise the coroutine is started and the next level is loaded both in the same frame. The coroutine only effects and pauses code inside of itself. It doesn’t make a pause before the next line directly after it is called.

I find using invoke much easier then using coroutines

using UnityEngine;
using System.Collections;
 
public class FinishLevel : MonoBehaviour {
    public string LevelName;
    public float waitFor; 
 
    public void OnTriggerEnter2D (Collider2D other)
    {
        if (other.tag == "Player") {
            Invoke ("ChangeLevel", waitFor);
        }
    }
 
    public void ChangeLevel() {
        Application.LoadLevel(LevelName);
    }
}

Try re-ordering the script so that mymethod is above ontriggerenter.

Why not just use

var timerSwitch : boolean = false;
var timer : float;

Update()
{
     if(!timerSwitch)
   {
     timer = Time.time + 5.0;
   }

   if(timer <= Time.time && timerSwitch)// by requiring timerSwitch to be true you don't need to worry about always keeping timer greater than time(like at start or if you activate this script mid game)
    {
       Application.LoadLevel (LevelName);
    }

}

public void OnTriggerEnter2D (Collider2D other)
    {
        if (other.tag == "Player") {
            timerSwitch = true;
        }
    }