- Home /
Using yield wait for seconds in my script, correctly
I am using this script to check when all my "brick" objects are destroyed and then it loads the next level.
function Update(){
var bricks = GameObject.FindWithTag("brick"); //find gameobjects with the tag "brick" (you must therefore tag the enemies with "brick"
if(bricks == null){ //if no gameobjects with the tag "brick" are found
//change scene
Application.LoadLevel(Application.loadedLevel + 1);
}
}
What I want to do is have a delay when all the bricks are destroyed and display "stage complete" (or something like that) and play a sound. I have tried using yield WaitForSeconds (5); I placed it above application load level. But this does not work. I looked at the script reference but was left still confused. Can anyone help me to correctly place it in my script? I'm utter n00b at scripting, design is my strong point.
Answer by BiG · Mar 28, 2012 at 10:42 PM
I would modify the script as below. Just add the sound and the "stage complete" text!
var countdown = false;
function Update(){
var bricks = GameObject.FindWithTag("brick");
if(bricks == null && !countdown){
countdown = true;
NextLevel();
}
}
function NextLevel(){
yield WaitForSeconds (5);
Application.LoadLevel(Application.loadedLevel + 1);
}
thankyou very much for your help and input, got it working now :))
Answer by gregzo · Mar 28, 2012 at 09:36 PM
You cannot use yield in Update()! Instead of calling Application.LoadLevel, call a function which will yield WaitForSeconds(5) and then load the next level. Try it, if you still have trouble with it let me know!
so after the brick checking in function Update would I do a new one underneath like:
function Update(){
var bricks = GameObject.FindWithTag("brick"); //find gameobjects with the tag "brick" (you must therefore tag the enemies with "brick"
if(bricks == null){ //if no gameobjects with the tag "brick" are found
}
function pause then load(){
//wait for 5 seconds
WaitForSeconds(5);
//change scene
Application.LoadLevel(Application.loadedLevel + 1);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613065641im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to delay a function (how to use WaitForSeconds() and yield) 1 Answer
Coroutine not running after yield return new WaitForSeconds 3 Answers
Yield only working once? 0 Answers
Loop Animation with delay-variable 1 Answer
Make delay for spawn 3 Answers