728x90
코루틴이란?
- 특정 작업을 여러 프레임에 걸쳐 나누어 수행
- 특정 조건이 충족될 때 까지 기다리면서 코드 실행을 중단할 수 있도록 하는 강력한 기능
- 게임에서 비동기 작업을 처리하는 데 사용
- 시간 지연
- 애니메이션
- 비동기 입력 처리 등...
Update 함수와 코루틴의 차이점
Update 함수
- 매 프레임 호출
- 해당 프레임 내에서 모든 작업을 완료해야 함
- 작업이 길어질 경우 프레임 드랍이나 렉이 발생할 수 있음.
이 문제를 해결하기 위해 Unity에서는 시분할(time sharing)방식의 Coroutine 사용
코루틴을 사용하면 긴 작업을 여러 프레임에 걸쳐 분할하여 수행가능
작업이 완료될 때까지 기다리지 않고 프레임이 부드럽게 유지
코루틴 사용법
1. 코루틴 정의
- 코루틴은 IEnumerator 타입을 반환하는 메서드로 정의
- IEnumerator는 코루틴의 상태를 유지하고, 다음 단계로 진행하기 위해 호출될 때마다 상태를 복원
using UnityEngine;
using System.Collections;
public class CoroutineExample : MonoBehaviour
{
void Start()
{
// 코루틴 시작
StartCoroutine(MyCoroutine());
}
IEnumerator MyCoroutine()
{
// 코루틴 시작 시 출력
Debug.Log("Coroutine started");
// 1초 기다리기
yield return new WaitForSeconds(1.0f);
// 1초 후 출력
Debug.Log("1 second passed");
// 프레임 끝까지 기다리기
yield return null;
// 다음 프레임에서 출력
Debug.Log("Next frame");
// 코루틴 종료
yield break;
}
}
2. 코루틴 시작
- 코루틴은 StartCoroutine 메서드를 사용하여 시작
- 코루틴을 시작할 때는 코루틴 메서드의 이름을 전달하거나 IEnumerator를 반환하는 메서드를 호출할 수 있음.
StartCoroutine(MyCoroutine());
3. 코루틴 중단
- 코루틴을 중단하려면 StopCoroutine 메서드를 사용
- 특정 코루틴을 중단하려면 그 코루틴의 참조를 전달해야 함.
Coroutine myCoroutine;
void Start()
{
myCoroutine = StartCoroutine(MyCoroutine());
}
void StopMyCoroutine()
{
if (myCoroutine != null)
{
StopCoroutine(myCoroutine);
}
}
4. yield return 구문
yield return null; // 다음 프레임까지 대기
yield return new WaitForSeconds(float seconds); // 지정한 시간(초) 동안 대기
yield return new WaitForEndOfFrame(); // 모든 렌더링이 완료될 때까지 대기
yield return new WaitForFixedUpdate(); // 다음 고정 업데이트(physics step)까지 대기
yield return StartCoroutine(AnotherCoroutine()); // 다른 코루틴이 완료될 때까지 대기
코루틴 사용 예제
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour
{
// 적 캐릭터가 3초 동안 대기한 후 플레이어를 추격하는 예제
public Transform player;
public float chaseSpeed = 5.0f;
void Start()
{
StartCoroutine(ChasePlayerAfterDelay(3.0f));
}
IEnumerator ChasePlayerAfterDelay(float delay)
{
// 지연 시간 동안 대기
yield return new WaitForSeconds(delay);
// 추격 시작
while (true)
{
// 플레이어 방향으로 이동
transform.position = Vector3.MoveTowards(transform.position, player.position, chaseSpeed * Time.deltaTime);
yield return null;
}
}
}
참고 문헌 : https://docs.unity3d.com/kr/2021.3/Manual/Coroutines.html
728x90
'게임엔진 > Unity' 카테고리의 다른 글
Unity - OnMouseDown (0) | 2024.07.02 |
---|---|
Unity - GetAxis (0) | 2024.07.02 |
Unity - 선형 보간 (0) | 2024.07.02 |
유니티 게임 프로그래밍 패턴 - SOLID 원칙 (0) | 2024.06.19 |
유니티 - InspectorAttribute (0) | 2024.05.03 |