Coroutines let you pause and resume actions over time without stopping the whole program. This helps manage things that happen step-by-step or after delays.
0
0
Why coroutines handle time-based logic in Unity
Introduction
Waiting a few seconds before showing a message in a game
Making an animation play smoothly over time
Delaying an action without freezing the game
Repeating a task every few seconds
Handling timed events like power-ups or cooldowns
Syntax
Unity
IEnumerator ExampleCoroutine()
{
// Do something
yield return new WaitForSeconds(2f); // Wait for 2 seconds
// Do next thing
}Coroutines use IEnumerator and yield return to pause execution.
WaitForSeconds pauses the coroutine without freezing the whole game.
Examples
This coroutine waits 3 seconds then prints a message.
Unity
IEnumerator WaitAndPrint()
{
yield return new WaitForSeconds(3f);
Debug.Log("3 seconds passed");
}This coroutine repeats an action every second forever.
Unity
IEnumerator RepeatAction()
{
while(true)
{
Debug.Log("Action repeated every 1 second");
yield return new WaitForSeconds(1f);
}
}Sample Program
This program starts a coroutine that waits 2 seconds before printing a message. The game keeps running during the wait.
Unity
using UnityEngine; using System.Collections; public class CoroutineExample : MonoBehaviour { void Start() { StartCoroutine(ShowMessage()); } IEnumerator ShowMessage() { Debug.Log("Wait starts"); yield return new WaitForSeconds(2f); Debug.Log("2 seconds passed"); } }
OutputSuccess
Important Notes
Coroutines do not block the main game loop, so the game stays responsive.
You can pause coroutines with yield return and resume later.
Coroutines are great for timing without complicated timers.
Summary
Coroutines let you handle time delays smoothly.
They pause and resume code without freezing the game.
Use them for animations, waits, and repeated timed actions.