How to create a recursive call with Unity’s Coroutines


During the development of Super Stems I’ve had to deal with chain reaction. I started a battle with one tile, and if they win, the captured tile would start a battle, and this would happen recursively. For some reason, I have this battle method call on a different thread, in Unity’s terms, a Coroutine.

Now comes the question. How do I handle recursion with Coroutines? After looking around the doc and experimenting, I found a solution.

Here’s a sample code on how to make it work.

After calling the entry point to your recursive method StartBattle, inside, you have yield return a new Coroutine call to the recursive method. This way, the execution order will be correct. Try it out and see for yourself.

Output should be.