- Home /
WaitForSeconds not waiting
Heya guys, I'm a total C# n00b.
So I'm expanding on the Roll-a-ball Unity Tutorial. I want it to wait 5 seconds after picking up all the objects before advancing to the next level. My result is the level advances without waiting 5 seconds. This is what I have:
void Start() {
count = 0;
winText.text = "";
CountTextUpdate();
}
IEnumerator WaitForLevelSwitch() {
yield return new WaitForSeconds(5);
}
void OnTriggerEnter(Collider other) {
if (other.gameObject.tag == "PickUp") {
other.gameObject.SetActive(false);
count = count + 1;
CountTextUpdate();
}
}
void CountTextUpdate() {
countText.text = "Count: " + count.ToString();
if (count >= 9) {
winText.text = "YOU WIN";
WaitForLevelSwitch();
Application.LoadLevel("Level_2");
}
}
Thanks for any help!
JjStAr
Answer by GameVortex · Nov 21, 2013 at 11:21 AM
You need to use StartCoroutine for WaitForLevelSwitch() to work as a coroutine:
//At line 24.
StartCoroutine(WaitForLevelSwitch());
Also, your code will advance past line 24 immediately no matter what, so you have to put the level load into the coroutine instead, where it actually waits:
IEnumerator WaitForLevelSwitch() {
yield return new WaitForSeconds(5);
Application.LoadLevel("Level_2");
}
Also, I would recommend reading up on coroutines and how they work here.
Your answer
Follow this Question
Related Questions
Call another function during wait for seconds 1 Answer
WaitForSeconds using Update? 1 Answer
Yield WaitForSeconds not working > once in coroutine 1 Answer
Run Coroutine once, but finish Lerping 2 Answers
Yield/OnTriggerEnter Help C# 1 Answer