ABOUT PORTFOLIO GAMES DEVLOG DOCS TOOLS CONTACT
HOME > DOCS > Unity / C# > Coroutine vs C# async/await & Unity 6 Awaitable 비동기 프로그래밍 가이드Coroutine vs C# async/await & Unity 6 Awaitable Asynchronous Programming Guide
Unity / C# Intermediate Unity 2022.3+ / Unity 6

Coroutine vs C# async/await & Unity 6 Awaitable 비동기 프로그래밍 가이드Coroutine vs C# async/await & Unity 6 Awaitable Asynchronous Programming Guide

IEnumerator 코루틴의 한계와 WaitForSeconds 캐싱, UniTask 및 Unity 6 신규 Awaitable API 비교, 씬 전환 시 누수를 방지하는 CancellationToken 패턴.Comparing IEnumerator coroutines, WaitForSeconds caching, UniTask, and Unity 6's Awaitable API, along with CancellationToken patterns to prevent leaks on scene changes.

#Unity #C# #Coroutine #async-await #Awaitable #Unity6
핵심 개념전통적인 Coroutine은 작성하기 쉽지만 값 반환(return value)이 불가능하고 예외 처리(try-catch)가 까다롭습니다. C# Task는 멀티스레드 스케줄링으로 인해 유니티 메인 스레드 객체 접근 시 오류가 발생할 수 있습니다. Unity 6에서 도입된 Awaitable은 추가 GC 할당을 줄인 구조로 메인 스레드 전환과 지연 처리를 지원합니다.
Core ConceptTraditional Coroutine methods are simple to write but cannot return values directly and make exception handling (try-catch) difficult. Standard C# Task objects can cause errors when accessing Unity main-thread objects due to thread pool scheduling. Introduced in Unity 6, Awaitable supports main-thread switching and delayed execution with pooled, low-allocation semantics.

1. 3가지 비동기 방식 비교표1. Comparison of 3 Asynchronous Approaches

좌우로 밀어서 표 전체 내용을 확인하세요
비교 항목Coroutine (IEnumerator)Task / UniTaskUnity 6 Awaitable
반환값 전달불가 (Action 콜백 필요)가능 (Task<T> / UniTask<T>)가능 (Awaitable<T>)
try-catch 예외 처리yield 내부에서 catch 불가지원지원
GC 할당량반복 yield 시 발생UniTask: 0에 근접 / Task: 힙 할당struct 기반 0 (할당 없음)
오브젝트 파괴 시 동작자동 정지 (오브젝트 비활성 시)토큰 취소 없으면 고아 태스크로 누수destroyCancellationToken 기본 지원
권장 사용처단순 깜빡임 연출웹 통신, 복잡한 비즈니스 로직Unity 6 최신 게임플레이 시퀀스
Swipe horizontally to view the full table
FeatureCoroutine (IEnumerator)Task / UniTaskUnity 6 Awaitable
Return ValuesNot supported (Requires Action callback)Supported (Task<T> / UniTask<T>)Supported (Awaitable<T>)
try-catch Exception HandlingCannot catch around yield statementsSupportedSupported
GC AllocationsAllocated on repeated yield instructionsUniTask: Near 0 / Task: Heap allocation0 (Pooled / Struct-based)
Behavior on Object DestructionStops automatically (when deactivated)Leaks as orphan task without cancellation tokenBuilt-in destroyCancellationToken support
Recommended Use CaseSimple visual blink sequencesWeb requests, complex business logicUnity 6 gameplay sequences

2. 최신 Unity 6 Awaitable 패턴 구현2. Unity 6 Awaitable Pattern Implementation

ModernAsyncSequence.cs
using System;
using System.Threading;
using UnityEngine;

public class ModernAsyncSequence : MonoBehaviour
{
    [SerializeField] private SpriteRenderer spriteRenderer;

    private async void Start()
    {
        try
        {
            // destroyCancellationToken: 오브젝트가 파괴되면 자동으로 취소 예외 발생
            await PlayDamageBlinkAsync(5, 0.1f, destroyCancellationToken);
            Debug.Log("피격 깜빡임 연출 완료.");
        }
        catch (OperationCanceledException)
        {
            // 씬 전환이나 오브젝트 파괴 시 안전하게 탈출
            Debug.Log("연출이 취소되었습니다.");
        }
    }

    /// <summary>
    /// Unity 6 Awaitable 기반 제로 알로케이션 깜빡임 연출
    /// </summary>
    public async Awaitable PlayDamageBlinkAsync(int blinkCount, float interval, CancellationToken ct)
    {
        for (int i = 0; i < blinkCount; i++)
        {
            spriteRenderer.color = Color.red;
            // 지정 초 대기 (GC 할당 0)
            await Awaitable.WaitForSecondsAsync(interval, cancellationToken: ct);

            spriteRenderer.color = Color.white;
            await Awaitable.WaitForSecondsAsync(interval, cancellationToken: ct);
        }

        // 백그라운드 스레드에서 무거운 연산 후 메인 스레드로 안전 복귀
        await Awaitable.BackgroundThreadAsync();
        // [백그라운드 스레드]: 대용량 배열 정렬이나 패킷 압축 해제 등 수행
        int calculatedScore = CalculateHeavyData();

        await Awaitable.MainThreadAsync();
        // [메인 스레드 복귀]: 안전하게 유니티 오브젝트 업데이트
        Debug.Log($"연산 완료 결과: {calculatedScore}");
    }

    private int CalculateHeavyData()
    {
        int sum = 0;
        for (int i = 0; i < 1000000; i++) sum += i % 7;
        return sum;
    }
}
ModernAsyncSequence.cs
using System;
using System.Threading;
using UnityEngine;

public class ModernAsyncSequence : MonoBehaviour
{
    [SerializeField] private SpriteRenderer spriteRenderer;

    private async void Start()
    {
        try
        {
            // destroyCancellationToken: automatically throws OperationCanceledException when destroyed
            await PlayDamageBlinkAsync(5, 0.1f, destroyCancellationToken);
            Debug.Log("Damage blink sequence completed.");
        }
        catch (OperationCanceledException)
        {
            // Safely exit on scene transition or object destruction
            Debug.Log("Sequence was canceled.");
        }
    }

    /// <summary>
    /// Zero-allocation damage blink sequence using Unity 6 Awaitable
    /// </summary>
    public async Awaitable PlayDamageBlinkAsync(int blinkCount, float interval, CancellationToken ct)
    {
        for (int i = 0; i < blinkCount; i++)
        {
            spriteRenderer.color = Color.red;
            // Wait for specified seconds (0 GC allocation)
            await Awaitable.WaitForSecondsAsync(interval, cancellationToken: ct);

            spriteRenderer.color = Color.white;
            await Awaitable.WaitForSecondsAsync(interval, cancellationToken: ct);
        }

        // Switch to background thread for heavy computation, then return to main thread
        await Awaitable.BackgroundThreadAsync();
        // [Background Thread]: Perform large array sorting or packet decompression
        int calculatedScore = CalculateHeavyData();

        await Awaitable.MainThreadAsync();
        // [Main Thread]: Safely update Unity objects
        Debug.Log($"Calculation result: {calculatedScore}");
    }

    private int CalculateHeavyData()
    {
        int sum = 0;
        for (int i = 0; i < 1000000; i++) sum += i % 7;
        return sum;
    }
}

3. 레거시 Coroutine 최적화 팁3. Legacy Coroutine Optimization Tips

  • new WaitForSeconds 캐싱: 코루틴 루프 내에서 yield return new WaitForSeconds(0.1f)를 반복하면 매 호출마다 가비지가 발생합니다. 필드 변수로 private readonly WaitForSeconds _wait = new WaitForSeconds(0.1f);를 생성해 두고 재사용합니다.
  • 코루틴 핸들 캐싱: StopCoroutine(myCoroutine)을 안전하게 호출할 수 있도록 실행 시 Coroutine _handle = StartCoroutine(...) 형태로 변수를 보관해야 합니다.
  • Cache new WaitForSeconds: Repeating yield return new WaitForSeconds(0.1f) inside a coroutine loop allocates garbage on every iteration. Declare a field such as private readonly WaitForSeconds _wait = new WaitForSeconds(0.1f); and reuse it.
  • Cache Coroutine Handles: Store the running coroutine reference via Coroutine _handle = StartCoroutine(...) so you can reliably stop it with StopCoroutine(_handle).

프로젝트의 유니티 버전과 비동기 작업의 성격에 맞춰 Coroutine 캐싱과 Awaitable 패턴을 선택하고 취소 토큰(CancellationToken)을 연동하면, 씬 전환 시에도 안정적인 비동기 흐름을 유지할 수 있습니다.

Choosing between cached Coroutines and Awaitable patterns based on your Unity version and linking tasks to a CancellationToken ensures stable asynchronous execution across scene transitions.

참고자료 & 관련 링크