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

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;
}

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());

    
}

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.

You need to start it in a Coroutine

void Start()
{
StartCoroutine(waitsec());
}