- Home /
Nested Coroutine without yielding null at terminal condition
Hi there guys,
I'm using nested coroutines in order to execute a demanding task over a time period of a couple frames. I do this by calling the function recursively. However, since the function does not return anything when terminal conditions have been met it ends up as ''yield return null' somewhere higher up the chain. The following code has been tested and embodies the problem well.
It's initialized as: StartCoroutine(test(3));
IEnumerator test(int depth)
{
if(depth == 0) Debug.Log("DEPTH: " + depth);
else if (depth == 2) Debug.Log("DEPTH: " + depth);
else if (depth == 1) Debug.Log("DEPTH: " + depth);
else
{
yield return StartCoroutine(test(2));
yield return StartCoroutine(test(1));
yield return StartCoroutine(test(0));
}
}
As you can see, the code needs 3 frames to return
DEPTH: 2
DEPTH: 1
DEPTH: 0
Question: How can I call a function recusively within a Coroutine without having the recursive call end up as yield return; null in the end?
I'd like to intruduce an alternative predicate that yields return nulll; after a certain time period has been exceeded. I do not want to yield after every recusive call.
I'm not sure I understand what you want. Yield return null is what makes Unity wait a frame to call $$anonymous$$oveNext on the coroutine again. That's what enables for example to execute a demanding task over a time period as you said. If you get rid of that "yield return null" (Not sure if that's exactly what's happening but the behaviour seems to point towards that) then you wouldn't be able to run the demanding task over multiple frames, defeating the point.
Your answer
![](https://koobas.hobune.stream/wayback/20220612164745im_/https://answers.unity.com/themes/thub/images/avi.jpg)