코루틴 (Coroutine), 유니티이벤트

sejun-Lee·2025년 4월 18일

UnityEngine

목록 보기
6/12

코루틴 (Coroutine)

* 코루틴 (Coroutine)   -> 시간 절약 X! , 작업을 분산
 
* 작업을 다수의 프레임에 분산하여 처리하는 비동기식 작업
* 실행을 일시정지하고 중단한 부분부터 재개하여 처리하는 것으로 작업을 분산처리함
* 코루틴은 스레드가 아니며 코루틴의 작업은 메인 스레드에서 실행

IEnumerator Routine()   // 코루틴은 IEnumerator 을 사용
{
    yield return null;                      // Update 끝날 때
    yield return new WaitForSeconds(1f);    // n초간 기다리고, Update 끝날 때
    yield return new WaitForSecondsRealtime(1f);    // 현실시간 n 초간 기다리고, Update 끝날 떄
    yield return new WaitForFixedUpdate();          // FixedUpdate 끝날 때
    yield return new WaitForEndOfFrame();           // 프레임이 끝날 때 (LateUpdate 다음)

    yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.Space));  // 조건이 맞을때까지 대기
}

[SerializeField] Rigidbody rigid;
[SerializeField] float junpPower;

private Coroutine countDownCoroutine;

private void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        if (countDownCoroutine == null) // 코루틴이 없을때 1번사용 - 중복해서 여러번 작업하는것을 방지
        {
            countDownCoroutine = StartCoroutine(Routine());
        }
    }
    if (Input.GetKeyDown(KeyCode.Escape))
    {
        //StopCoroutine(Routine());   // 루틴을 멈추는 것이 아닌 코루틴 담당자를 멈춰야 함

        if (countDownCoroutine != null) // 코루틴이 있어야 멈출 수 있다.
        {
            StopCoroutine(countDownCoroutine);
            countDownCoroutine = null;   // 다시 초기화 해줘야 재사용 가능.
        }
    }

}


 <코루틴 반복 작업>
//IEnumerator를 반환형으로 함수를 구성

IEnumerator Routine()   // 코루틴은 IEnumerator 을 사용
{
    WaitForSeconds delay = new WaitForSeconds(1f);  // 아래 방법보다 이방법을 권장. 계속 new 하면 메모리 누수
    Debug.Log(5);
    yield return delay;     // yield 일서정지, 양보
    Debug.Log(4);
    yield return delay;
    Debug.Log(3);
    yield return delay;
    Debug.Log(2);
    yield return delay;
    Debug.Log(1);
    yield return delay;


    Debug.Log(5);
    yield return new WaitForSeconds(1f);	// 아래 방법
    Debug.Log(4);
    yield return new WaitForSeconds(1f);
    Debug.Log(3);
    yield return new WaitForSeconds(1f);
    Debug.Log(2);
    yield return new WaitForSeconds(1f);
    Debug.Log(1);
    yield return new WaitForSeconds(1f);

    Debug.Log("점프 대기 시작");
    yield return new WaitForSeconds(5f);    // yield는 뒤에 조건만큼 기다리다가 -> 5초 뒤에
    Debug.Log("점프!!");
    rigid.AddForce(Vector3.up * junpPower, ForceMode.Impulse);  // 점프 시작

    countDownCoroutine = null;  // 다시 초기화 해줘야 재사용 가능.

    //yield return WaitUntil -> 사용으로 중간에 멈췄다 다시 사용 가능
}

유니티이벤트

public class UnityEventTester : MonoBehaviour
{
    public UnityEvent myEvent;  // 유니티 이벤트 사용 -> 클래스
    //public UnityEvent<int> myEvent;   //매개변수 있는 이벤트

    //public event Action<int> OnHpChanged;

    public event UnityAction OnDied;    // UnityAction -> 델리게이트
    public event Action myDelegate;     // UnityAction 과 같은 거임. 차이 없음.

    private void Awake()
    {
        //myEvent.AddListener(Test); // AddListener 로 함수를 추가 해서 사용 가능
        //myEvent.RemoveListener(Test);

        //OnHpChanged += Test;
        //OnHpChanged += Func;
    }

    public void Test(){}

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            myEvent.Invoke(); // Invoke 로 발생시키다.
            //myEvent.Invoke(10); // 매개변수 있는 경우
        }
    }
}
profile
초보 개발자

0개의 댓글