- Home /
Coroutine and Loops
Hi there, I'm using coroutines to drive a character behaviour:
void Start ()
{
m_rigidbody = GetComponent<Rigidbody2D> ();
m_characterProperties = GetComponent<CharacterProperties> ();
StartCoroutine (StartBehaviour ());
}
IEnumerator StartBehaviour ()
{
m_timer = 0f;
while (m_timer < 2.0f) {
m_timer += Time.deltaTime;
yield return null;
}
StartCoroutine (Check ());
}
So in the above example, I wait two seconds then call the Check() coroutine (not shown for clarity) - this all works fine. However, I basically want to loop this behaviour - so I want the logic to repeat (so wait two seconds, then call Check again, repeat). However, I'm a little lost how to best do this - any suggestions? Thanks!
Answer by Eno-Khaon · Apr 02, 2015 at 05:26 PM
Here's a heavy-handed way of approaching it:
IEnumerator StartBehaviour ()
{
while(true) {
m_timer = 0f;
while (m_timer < 2.0f) {
m_timer += Time.deltaTime;
yield return null;
}
StartCoroutine (Check ());
m_timer = 0.0f;
yield return null;
}
}
That way, the "StartBehaviour" Coroutine continues endlessly and the timer resets every time it's successful.
Dependign on what Check actually does, you might want to use
yield return StartCoroutine (Check ());
Which will make the StartBehaviour coroutine to wait for the Check coroutine to finish before it restarts the loop. Otherwise if Check needs for example 1.5 seconds to complete, a new Check will be started 0.5 seconds after the old one has finished. If you yield the coroutine it will start the 2 seconds waiting time after Check has finished.
If Check would actually take longer than 2 seconds to finish, 3 sec. for example, StartBehaviour would start a new Check coroutine event the old one hasn't finished yet. So for 1 sec. There would run two Check coroutines at once. Depending on what the coroutine does this might be a huge problem.
Thanks for all the responses guys - made everything a little clearer!
Answer by UNZoOM · Apr 02, 2015 at 04:53 PM
If you dont want to stick to coroutine then follwoing will work. Wait for 2 seconds and call Check func , followed by repeated call every 2 seconds.
InvokeRepeating("Check", 2,2);
I was specifically wanting to use coroutines - but thanks for the response!
w.r.t coroutines..
void Start ()
{
StartCoroutine("StartBehaviour ");
}
IEnumerator StartBehaviour ()
{
while(true)
{
yield return new WaitForSeconds(2);
StartCoroutine (Check ());
}
}
Your answer