Coroutines with Unity3D and C#

Alberto Garcia
2 min readDec 15, 2022

--

Coroutines serve great to give rhythm and cycles to the game. These methods create an experience with cadence and usually are the pieces of code that make players stop smashing the buttons every millisecond and actually play their fingers and input along with the visual animations of the game. They provide time to breath, time to build up tension, time to accomplish cycles and time to WaitForSeconds(_hahaFunny).

WaitFor light color to change.

On a prior post about cool-down mechanics, an IEnumerator(method) was used to create a fraction-of-a-second pause before the shooting system could fire again. Coroutines & YieldInstructions in the manual. In order to use any of the YieldInstructions, they must be placed inside an IEnumerator method(). The next example shows how to run a coroutine within another coroutine:

public class ExampleClass : MonoBehaviour
{
void Start()
{
StartCoroutine(coroutineA());
}

IEnumerator coroutineA()
{
// wait for 1 second
Debug.Log("coroutineA created");
yield return new WaitForSeconds(1.0f);
yield return StartCoroutine(coroutineB());
Debug.Log("coroutineA running again");
}

IEnumerator coroutineB()
{
Debug.Log("coroutineB created");
yield return new WaitForSeconds(2.5f);
Debug.Log("coroutineB enables coroutineA to run");
}
}

When starting, coroutine A begins, it sends the first Log message, it waits for 1 second, it starts coroutineB and pauses while coroutine B is executing. CoroutineB starts by sending a log message, waiting for 2.5 seconds and after sending the last log message, coroutineA resumes by executing the final line and sending its last Log message.

The key to cycling smartly through coroutines is to have well usage of booleans and other methods that synchronize one method routine to the next one, checking for null errors, and establishing run-time parameters that work according to the script design.

--

--

Alberto Garcia
Alberto Garcia

No responses yet