- Home /
yield return new WaitForSeconds Not Working
Hi all! I wrote this code:
public GameObject TheBox;
public bool ready = true;
// Update is called once per frame
void Update () {
if(ready){
MakeBox();
}
}
IEnumerator waitsec() {
yield return new WaitForSeconds(2);
}
void MakeBox()
{
ready=false;
Instantiate (TheBox,transform.position,transform.rotation);
StartCoroutine (waitsec());
ready=true;
}
I am expecting that a box will be created on scene every 2 secands. but it keep creating boxes each frame it is a mess...Can anyone help?? please
Answer by Psymon · Jan 22, 2013 at 01:32 PM
It keeps creating boxes each frame because you don't wait the seconds because you don't yield on your MakeBox function. Try something like this :
void Update () {
if(ready){
StartCoroutine(MakeBox());
}
}
IEnumerator MakeBox()
{
ready=false;
Instantiate (TheBox,transform.position,transform.rotation);
yield return new WaitForSeconds(2);
ready=true;
}
Answer by jonc113 · Jul 01, 2014 at 11:12 PM
Just to point out, both of these answers solve the problem by putting WaitForSeconds in the body of the routine, instead of a separate routine.
It is certainly simpler to do this, but the original code will work if you just use the line:
yield return StartCoroutine (waitsec());
(C# version) This ensures that the coroutine completes before moving on.
Answer by PAEvenson · Jan 22, 2013 at 01:32 PM
You need to add the code to the Coroutine. The code after you call "StartCoroutine()" will still get executed that frame. try this:
void Update () {
if(ready){
MakeBox();
}
}
IEnumerator waitsec() {
ready=false;
yield return new WaitForSeconds(2);
Instantiate (TheBox,transform.position,transform.rotation);
ready=true;
}
void MakeBox()
{
StartCoroutine (waitsec());
}
Answer by blenderblender · Jan 19, 2015 at 02:32 PM
You need to start it in a Coroutine
void Start() { StartCoroutine(waitsec()); }
Your answer
![](https://koobas.hobune.stream/wayback/20220613091408im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Yeild and WaitForSeconds and Instantiate 1 Answer
Access a instantiated gameobject from a enemy spawner 4 Answers
Rotate "ghost object" then instantiate object with that rotation 1 Answer
Combine objects instantiated at runtime 2 Answers
NullReferenceException: Object reference not set to an instance of an object 2 Answers