I'm using the StartCoroutine method of Unity3D and I have a question concerning nested coroutines.
Typically, nested coroutines might look something like this:
void Start() { StartCoroutine(OuterCoroutine()); }
IEnumerator OuterCoroutine()
{
//Do Some Stuff . . .
yield return StartCoroutine(InnerCoroutine());
//Finish Doing Stuff . . .
}
IEnumerator InnerCoroutine()
{
//Do some other stuff . . .
yield return new WaitForSeconds(2f);
//Finish Doing that other stuff . . .
}
That's all well and fine, but it's really not necessary. The same effect can be achieved like this:
void Start() { StartCoroutine(OuterCoroutine()); }
IEnumerator OuterCoroutine()
{
//Do Some Stuff . . .
IEnumerator innerCoroutineEnumerator = InnerCoroutine().GetEnumerator();
while(innerCoroutineEnumerator.MoveNext())
yield return innerCoroutineEnumerator.Current;
//Finish Doing Stuff . . .
}
IEnumerable InnerCoroutine()
{
//Do some other stuff . . .
yield return new WaitForSeconds(2f);
//Finish Doing that other stuff . . .
}
I have found this method produces less garbage (which can be an issue in Unity) than having multiple StartCoroutines; therefore it is very useful, especially when dealing with many nested layers.
Now my question is:
Instead of using IEnumerable InnerCoroutine(){}
and getting the enumerator like so:
IEnumerator innerCoroutineEnumerator = InnerCoroutine().GetEnumerator();
I'd like to use IEnumerator InnerCoroutine(){}
and get the enumerator like this:
IEnumerator innerCoroutineEnumerator = InnerCoroutine();
Are they the same?
In addition to being faster in my testing, this method will allow me to use the "inner coroutine" method via the normal StartCoroutine method, which might useful down the road.
I have done testing, and as far as I can tell, both techniques are effectively doing the same thing, but I am still relatively new at this whole coding thing, so there is the chance that I am missing something.
Indeed, both way of writing produce the same result.
This is more a C# question, Unity3D is just using those type in their coroutine system. You might find this post answering in more details your question.
However, I am not sure what you mean by
I have found this method produces less garbage (which can be an issue in Unity)
since both method should produce the same result.At this point it's more of a choice of code style.
I personally prefer the StartCoroutine(InnerCoroutine())
one liner, where InnerCoroutine()
would return an IEnumerator
. I don't see the point in returning an IEnumerable for InnerCoroutine()
and then getting its enumerator afterwards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With