- Home /
Coroutine not working - what I did wrong?
Can anyone explain to me why this coroutine won't work ? I used Start Coroutine and it builds fine, but It doesn't wait for the seconds.
public class count : MonoBehaviour {
public int counter = 0;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
StartCoroutine (countUpdate());
}
IEnumerator countUpdate()
{
counter += 135;
yield return new WaitForSeconds(1f);
Debug.Log (counter);
}
}
starting coroutines in Update()
is a bad idea. you state that it doesn't wait for the seconds - what does it do?
As gjf said. This code will start a coroutine every time Update() is called (I believe). If you want it to repeat you should put a while-loop inside the coroutine (while(true)?) and start it from the Start()-function.
Answer by slimsterstanley · Dec 06, 2015 at 02:41 PM
Both guys are right.
I haven't tested it but you could just do this :
public class count : MonoBehaviour {
public int counter = 0;
// Use this for initialization
void Start ()
{
InvokeRepeating("countUpdate", 0.0f, 1f);
}
void countUpdate()
{
counter += 135;
Debug.Log (counter);
}
}
Answer by Bunny83 · Dec 05, 2015 at 10:00 PM
Like @gif and @Salmjak said starting a coroutine every frame is not a good idea. The coroutine does work as expected. Each frame you start a new coroutine. Each coroutine will immediately add 135 to your counter variable. So you have an increase of 135 each frame. Each coroutine will wait for 1 second and after one second they print the current counter value. Since you start a new coroutine every frame after the first second the first started coroutine will complete and print the debug log. From now on each frame another coroutine will finish since you started a new one each frame.
What you might want to do is something like this:
public class count : MonoBehaviour
{
public int counter = 0;
void Start ()
{
StartCoroutine (countUpdate());
}
IEnumerator countUpdate()
{
while (true)
{
counter += 135;
yield return new WaitForSeconds(1f);
Debug.Log (counter);
}
}
}
This way you start one coroutine which will loop forever. It will complete one iteration every second.
Your answer
![](https://koobas.hobune.stream/wayback/20220612051318im_/https://answers.unity.com/themes/thub/images/avi.jpg)