- Home /
Running a coroutine without StartCoroutine
I use coroutines for a lot of my initialization code, yielding frequently to reduce stutter on loading screens, etc.
However, sometimes I want all of my initialization to happen "all at once" (i.e in a blocking fashion, like a normal method, all in one frame). Previously, I have been duplicating my initialization code into coroutine and non-coroutine methods - I'd like to avoid this so I can reduce the amount of code I need to test and debug.
I've discovered that I can "run" the coroutine by iterating through it like a normal Enumerator - see code below.
Is what I'm doing supported? I can't see any disadvantages, or anything that will break, so far in my testing.
Thanks!
void Start()
{
IEnumerator enumerator = MyCoroutine();
while(enumerator.MoveNext())
{
}
Debug.LogError("Complete");
}
IEnumerator MyCoroutine()
{
Debug.LogError("Coroutine Start");
yield return new WaitForSeconds(3.0f);
Debug.LogError("Coroutine End");
}
It seems that yielding to a StartCoroutine() call in your Enumerator coroutine means that the child coroutine will behave as if it were started separately; e.g. it will run while yielding, not all at once like the parent coroutine.
So the above technique will work as long as you don't start coroutines in the IEnumerator that you are running
This code should interest you http://wiki.unity3d.com/index.php?title=CoroutineScheduler
Looks interesting, Sisso. However I'd rather not include an entire new coroutine system just for my own convenience on a few initialization routines - I think I'll stick with my duplicated code for now.
Answer by Sisso · Jan 28, 2015 at 02:03 PM
The problem is that it open a door for possible bugs. Each coroutine return type have a meaning, and you are not respecting it. For example, I can insert yield return 0 after create many objects so I only continue after everything get fully initialized.
If is not causing problem and you know what are you doing, go on, no time to waste :P
In the long term a proper abstraction for lazy load should be a better idea, so you can control loads per time, have progress, retry, etc.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Loop Coroutine For A Demo Mode 1 Answer
Distribute terrain in zones 3 Answers
Is there a way to find out when a coroutine is done executing? 3 Answers