강의, 책/[Unity] C#과 유니티로 만드는 MMORPG 게임 개발 시리즈

Section 11. Coroutine

hye3193 2024. 2. 3. 23:34

코루틴을 사용하면 이전에 함수에서 진행 중이던 상황을 저장했다가 복원하여 그대로 이어서 수행하게 할 수 있다

* yield break; 를 하게 되면 함수를 완전히 빠져나오게 된다

// 코루틴 사용 예
StartCoroutine("CoExplodeAfterSeconds", 4.0f);

IEnumerator CoExplodeAfterSeconds(float seconds)
{
    Debug.Log("Explode Enter");
    yield return new WaitForSeconds(seconds);
    Debug.Log("Explode Execute!");
}
// 코루틴 사용 및 삭제
Coroutine co = StartCoroutine("CoExplodeAfterSeconds", 4.0f);
StartCoroutine("CoStopExplode", 2.0f);

IEnumerator CoStopExplode(float seconds)
{
    Debug.Log("Stop Enter");
    yield return new WaitForSeconds(seconds);
    Debug.Log("Stop Execute!");
    if (co != null)
    {
        StopCoroutine(co);
        co = null;
    }
}

IEnumerator CoExplodeAfterSeconds(float seconds)
{
    Debug.Log("Explode Enter");
    yield return new WaitForSeconds(seconds);
    Debug.Log("Explode Execute!");
    co = null;
}

* 코루틴 계열의 함수는 함수명에 Co를 붙여주면 구별이 용이