WaitForSeconds doesn't work in Coroutine.

Hey Guys,
I am having some problems lately with coroutines. Somehow the code executes the LoadScene right after the if-statement equals true and I don’t know why. It should wait 10 seconds. The canPass from GameManager is a boolean.

public class Finish : MonoBehaviour {

	public Camera cam;
	public GameObject player;
	public ParticleSystem particle;

	private Animator anim;

	void Start ()
	{
		anim = GetComponent<Animator> ();
	}

	void Update()
	{
		if (cam.GetComponent<GameManager> ().canPass)
			anim.SetTrigger ("activate");
	}

	void OnCollisionEnter()
	{
		if (gameObject.name == "playerCube" && cam.GetComponent<GameManager> ().canPass)
		{
			StartCoroutine (WaitForLoad ());
		}
	}

	IEnumerator WaitForLoad()
	{
		yield return new WaitForSeconds (10f);
		SceneManager.LoadScene (cam.GetComponent<GameManager> ().nextScene);
	}
}
  1. Try to remove the F after the number
  2. Try to start the Coroutine with StartCoroutine(“WaitForLoad”)
  3. If this doesn’t solve your problem, use Debug.Log() before and after the WaitForSeconds() and in the if-statement.

EDIT: I tried your script and it works perfectly for me. Maybe there is another script that is accidentally loading the scene?

Hi,

I think what you want is WaitForSecondsRealtime(). Check out the links below for more description. As the name suggests, this function waits for the amount of time specified in real-time.

If you want an example to see how this command is implemented, check out the below link

Hope this helps,
Pranav

The yield return new WaitForSeconds (10f); should work. I believe that the problem lies somewhere else. You should instead check if the coroutine WaitForLoad() is being started at the correct instant.
You could try using Debug.log in the if block as well as a Debug.log in the beginning of WaitForLoad().

Also, for something like this, you don’t really need a coroutine, you could instead use Invoke(). It is simpler and easier.