새소식

⇥ 2D Game/Unity

Unity 게임 만들기 프로젝트 - Coroutine

  • -
반응형

1. Unity Coroutine

특정 함수가 긴 작업이라, 나눠서 수행되도록 하거나, 조건이 만족되면 다음 코드를 수행하거나, 진행 되다가 외부 요인으로 인해 끊어야 하는 등의 다양한 경우가 있을 수 있다. 이런 경우에 함수를 나눠서 실행하도록 돕는 것이 Coroutine 이다.

Coroutine co;

Coroutine 이라는 co 를 생성해준다.

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 ExplodeAfterSeconds(float seconds)
    {
        Debug.Log("Explode Enter");
        yield return new WaitForSeconds(seconds);
        Debug.Log("Exploded!!!!");
        co = null;
    }

IEnumerator 로 반환하는 Coroutine 함수들을 생성해주었는데, 반환 타입은 캐스팅해서 사용하면 된다.

ExplodeAfterSeconds 는 입력받은 초 만큼 기다렸다가 Exploded 라는 로그를 뱉고, co 를 초기화 해주는 함수이며,
CoStopExplode 는 입력받은 초 만큼 기다렸다가 Stop 로그를 뱉고, co 를 초기화 해준다. 

co = StartCoroutine("ExplodeAfterSeconds", 4.0f);
        StartCoroutine("CoStopExplode", 2.0f);

        StopCoroutine(co);

StartCoroutine 을 사용해서 explodeAfterSeconds 를 4초에 입력하면, Explode Enter 후 4초 후에 Exploded 가 출력될 것이다.
하지만 CoStopExplode 를 2초로 실행해주니, 바로 Stop Enter 로그가 출력되고, 2초 후에 코루틴이 제거되어 Exploded 를 볼 수 없다.

 

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.