[기초] Unity3D에서 코루틴(Coroutine) 완벽 가이드
1. 개요
코루틴(Coroutine)은 Unity3D에서 시간 기반 작업을 효율적으로 처리하는 강력한 도구입니다. 게임에서 특정 작업을 일정 시간 간격으로 반복하거나, 특정 조건이 충족될 때까지 대기하도록 만들고 싶을 때 유용합니다. 이번 게시글에서는 코루틴을 사용하는 방법과 함께 실전 예제를 통해 효율적인 사용 방법을 살펴보겠습니다.
2. 코루틴의 기본 개념
Unity의 코루틴은 IEnumerator 인터페이스를 사용하며, 시간 단위로 작업을 나누어 실행합니다. 코루틴은 StartCoroutine() 메서드로 실행되며, 특정 조건에서 실행을 중단하거나 재개할 수 있습니다.
2.1 기본적인 코루틴 구조
using UnityEngine;
public class CoroutineExample : MonoBehaviour
{
void Start()
{
StartCoroutine(MyCoroutine(2f));
}
IEnumerator MyCoroutine(float delaySeconds)
{
Debug.Log("코루틴 시작");
yield return new WaitForSeconds(delaySeconds);
Debug.Log($"{delaySeconds}초 후 실행");
}
}
2.2 주요 키워드
- yield return null: 다음 프레임까지 대기합니다.
- yield return new WaitForSeconds(time): 지정된 시간(초) 동안 대기합니다.
- yield return new WaitUntil(condition): 조건이 참이 될 때까지 대기합니다.
- yield return new WaitForEndOfFrame: 현재 프레임의 렌더링이 끝날 때까지 대기합니다.
3. 코루틴의 다양한 활용 사례
3.1 반복적인 동작 처리
다음은 오브젝트가 일정 시간 간격으로 이동하도록 하는 예제입니다.
using UnityEngine;
public class MoveObject : MonoBehaviour
{
public float speed = 2f;
void Start()
{
StartCoroutine(Move());
}
IEnumerator Move()
{
while (true)
{
transform.Translate(Vector3.right * speed * Time.deltaTime);
yield return null; // 매 프레임마다 실행
}
}
}
3.2 조건부 대기
특정 조건이 충족될 때까지 대기하도록 만들 수 있습니다.
using UnityEngine;
public class WaitForCondition : MonoBehaviour
{
public bool isReady = false;
void Start()
{
StartCoroutine(WaitUntilReady());
}
IEnumerator WaitUntilReady()
{
Debug.Log("조건 대기 중...");
yield return new WaitUntil(() => isReady); // isReady가 true가 될 때까지 대기
Debug.Log("조건 충족!");
}
}
3.3 코루틴 중단 및 재개
코루틴을 동적으로 중단하거나 재개할 수 있습니다.
using UnityEngine;
public class PauseResume : MonoBehaviour
{
private Coroutine currentCoroutine;
void Start()
{
currentCoroutine = StartCoroutine(MyCoroutine());
}
IEnumerator MyCoroutine()
{
while (true)
{
Debug.Log("코루틴 실행 중...");
yield return new WaitForSeconds(1f);
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.P))
{
if (currentCoroutine != null)
{
StopCoroutine(currentCoroutine);
Debug.Log("코루틴 중단");
}
}
if (Input.GetKeyDown(KeyCode.R))
{
if (currentCoroutine == null)
{
currentCoroutine = StartCoroutine(MyCoroutine());
Debug.Log("코루틴 재개");
}
}
}
}
3.4 Start 콜백을 코루틴으로 변경
MonoBehaviour의 Start 콜백을 코루틴으로 변경할 수 있습니다.
using UnityEngine;
public class PauseResume : MonoBehaviour
{
private Coroutine currentCoroutine;
IEnumerator Start()
{
yield return new WaitForSeconds(1f);
Debug.Log("코루틴...");
}
}
4. 코루틴 사용 시 주의점
- 무한 루프에 주의: 코루틴이 무한히 실행되지 않도록 종료 조건을 명확히 해야 합니다.
- StopCoroutine의 정확한 사용: StopCoroutine()을 호출할 때 올바른 참조를 사용해야 중단이 가능합니다.
- 성능 관리: 너무 많은 코루틴을 동시에 실행하면 성능에 영향을 줄 수 있습니다. 필요 없는 코루틴은 중단하세요.
- 게임오브젝트 활성화여부: 게임오브젝트가 비활성화되어 있을 때엔 실행할 수 없습니다. 시작된 코루틴 역시 게임오브젝트가 비활성화될 때 정지됩니다.
Coroutine couldn't be started because the the game object 'go' is inactive!
UnityEngine.MonoBehaviour:StartCoroutine (System.Collections.IEnumerator)
5. 결론
Unity3D에서 코루틴은 시간 기반 작업을 간단하고 효율적으로 처리할 수 있는 도구입니다. 이번 게시글에서는 코루틴의 기본 사용법부터 조건부 대기, 반복 동작, 중단 및 재개까지 다양한 활용 사례를 살펴보았습니다. 프로젝트에서 코루틴을 적극 활용하여 동적이고 유연한 게임 동작을 구현해 보세요!
| 참고
코루틴의 어떤 원리로 구현되었는지는 아래 게시글의 DelayedCallManager 부분을 참고
코루틴 - Unity 매뉴얼
코루틴을 사용하면 작업을 다수의 프레임에 분산할 수 있습니다. Unity에서 코루틴은 실행을 일시 정지하고 제어를 Unity에 반환하지만 중단한 부분에서 다음 프레임을 계속할 수 있는 메서드입니
docs.unity3d.com