유니티 스크립트

코루틴(Coroutine)

ruripanda 2024. 12. 24. 23:21

 

using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
	void Start()
    {
    	// 코루틴 시작 
    	StartCoroutine(MyCoroutine());
    }
    IEnumerator MyCoroutine()
    {
    	// 2초 동안 기다림
    	yield return new WaitForSeconds(2f);
    	//2초 후에 실행될 코드
    	Debug.Log("2초 후 작업 실행");
    }
    //코루틴 정지
    StopCoroutine(MyCoroutine)
    //이 스크립트에서 실행되는 모든 코루틴 정지
    StopAllMyCoroutine();
}

 

코루틴의 기본 구조

코루틴은 IEnumerator를 반환하는 메서드로 정의됩니다. 예를 들어, 일정 시간 동안 기다린 후 작업을 수행하는 코루틴은 다음과 같이 작성할 수 있습니다

 

IEnumerator DelayedAction(float delay)
{
    yield return new WaitForSeconds(delay);
    Debug.Log("지연 후 작업 실행");
}

 

시간 지연처리 코드

 

IEnumerator MoveOverTime(Transform target, Vector3 end, float duration)
{
    Vector3 start = target.position;
    float elapsed = 0f;

    while (elapsed < duration)
    {
        target.position = Vector3.Lerp(start, end, elapsed / duration);
        elapsed += Time.deltaTime;
        yield return null; // 다음 프레임까지 대기
    }

    target.position = end; // 최종 위치 설정
}

 

점진적 변화

코루틴 사용 방법

코루틴은 StartCoroutine을 통해 시작하며, yield 키워드를 사용하여 중단할 수 있습니다. 특정 조건을 만족하면 다시 실행됩니다.

코루틴은 네트워크 요청, 애니메이션, 타이머 등의 여러 비동기적 작업에 유용하게 사용할 수 있습니다