Pages

Thursday, March 21, 2013

Unity3D + C#: Nested Coroutine (Coroutine within a Coroutine)

To call a coroutine inside a coroutine, like how you would normally call a function within a function:

// function within a function
void Attack()
{

}

void Battle()
{
Attack();
}


// coroutine within a coroutine
// the about-to nested coroutine also have to be an IEnumerator method
IEnumerator AttackCoroutine()
{
yield return new WaitForSeconds(1);
Debug.Log("Attack");
}

IEnumerator BattleCoroutine()
{
// call the method using "yield return StartCoroutine(FunctionHere())"
yield return StartCoroutine(AttackCoroutine());
yield return new WaitForSeconds(1);
Debug.Log("Defend");
}

Source: http://answers.unity3d.com/questions/14081/nested-coroutines.html