Coroutine not waiting for a set amount of time!
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class TestCOntorller : MonoBehaviour { public GameObject x; private float z,c; void Start () {
}
// Update is called once per frame
void Update () {
StartCoroutine (kocence ());
}
IEnumerator kocence(){Debug.Log ("dadD");
z = Random.Range (1f, 2f);
if (z <= 1.5) {
c = 0.3f;
} else {
c = 1.8f;
}
Instantiate (x, new Vector3 (2.93f, c, 0f),Quaternion.identity);
yield return new WaitForSeconds(10);
//Debug.Log ("dadD");
}}
My goal is to wait after every instantiate and not spam the screen with GameObjects .The Debug.Log does appear when i run the game "Debug.Log ("dadD");" so the problem should be in the yield or at least i think so . I have no expiriance with coroutins thus any help willl be appriciated.
Answer by jdean300 · May 21, 2017 at 03:49 AM
The problem is that you are starting a new coroutine in every update. What you want to do is this:
public bool spawning = false;
private void Start()
{
StartSpawning();
}
public void StartSpawning()
{
spawning = true;
StartCoroutine(kocence())
}
public void StopSpawning()
{
spawning = false;
}
IEnumerator kocence(){
while (spawning) {
Debug.Log ("dadD");
z = Random.Range (1f, 2f);
if (z <= 1.5) {
c = 0.3f;
} else {
c = 1.8f;
}
Instantiate (x, new Vector3 (2.93f, c, 0f),Quaternion.identity);
yield return new WaitForSeconds(10);
}
}
Careful, this solution could lead into multiple coroutines spawning in parallel, if you use StopSpawning and then StartSpawning before the coroutine gets to the while(spawning) check. Ins$$anonymous$$d, save the Coroutine handle returned by StartCoroutine and use that with StopCoroutine call.
Thank you! I was going insane trying to figure out why my coroutine wasn't waiting. It was because the Update() method was creating new coroutines each frame. The individual coroutines were waiting, but it seemed like they weren't since so many of them had instantiated. To fix this I created a boolean called "waiting" and set it to true before the waitForSeconds and set it false after I completed my delay. And I only called the coroutine if "waiting" was false.
Your answer
![](https://koobas.hobune.stream/wayback/20220612122358im_/https://answers.unity.com/themes/thub/images/avi.jpg)