- Home /
Running coroutines in a recursive function. How to wait until all coroutines done before going to next level
I've got a coroutine which moves the position of several gameobjects in a hierarchy. The general structure is like this:
void someFunction()
{
...
if (value)
someFunction()
...
Func1()
}
void Func1()
{
StartCoroutine(Func2(root))
}
IEnumerator Func2(Node node)
{
StartCoroutine(Func2(node.child))
}
It's a little more nested than that, and there's a couple of coroutines in there. One is recursive, and one runs on the parent of the current root (if it has one).
I know it's fairly specific, but in essence, I'd like to wait after the someFunction
call inside itself before running any further. I do this to move up an down a tree and traverse it one by one instead of straight to it. Any ideas?
To get the end moment of the coroutine you can make the coroutine call a function or send an event in its last line.
The function can be called using delegates or by harcoding it (calling the name of the function itself). If you just want to check for the end of the coroutine I suggest you make the coroutine send an event. (and the event handler can do whatever you need)
Just use a bool like this: bool running;
void Invoke$$anonymous$$yCoroutine()
{
StartCoroutine("Coroutine");
}
IEnumerator Coroutine()
{
running= true;
//do Stuff
yield return //Whatever you want
running= false;
}
// As long as you a within this scope you can just do :
void AnotherFunction()
{
if (running)
{
// Do some other stuff;
}
}
I did try this, but because I'm running several, I tried making a list of IEnumerators and then loop through each one, waiting for them to finish and yield them, then at the end set a bool to say they're all finished, and then I stuck a while (coroutinesRunning)
after it, but alas it just hung.
There's -a lot- of code. The above is a $$anonymous$$WE of the problem.
Answer by m-coto · May 18, 2017 at 11:02 AM
Your someFunction should be an IEnummerator and you should wait for the inner coroutines to be finished using something like this:
yield return StartCoroutine(Func2(root));
That should only continue to run code when the coroutine it's calling has finished.