경일게임아카데미 멀티 디바이스 메타버스 플랫폼 개발자 양성과정 20221101 개인 공부 2022/04/04~2022/12/14

Jinho Lee·2022년 11월 1일
0

2022.11.01 개인 학습 - 코루틴 사용의 유의점

코루틴 사용 유의점

  • StartCoroutine에서는 메서드의 이름이나 메서드 자체(IEnumerator)를 써서 제대로 작동했는데, StopCoroutine을 사용하면 제대로 정지하지 않는 문제가 많았다.

  • 그 이유는 IEnumerator 메서드를 실행할 때마다 참조값이 바뀌기 때문이다.

    • IEnumerator은 열거자로, C++의 Iterator(반복자)와 같은 역할을 한다.

    • 그렇기에 매번 다음 요소로 이동한다.

  • 따라서 다음과 같이 Coroutine이나 IEnumerator 변수를 선언, 할당하고 사용해야 한다.

    • Coroutine

      public class Wood : FocusableObjects
      {
          private static readonly YieldInstruction COUNT_DOWN = new WaitForSeconds(3f);
          private const int CAMPFIRE_LAYER = 11;
      
          private Coroutine _countDown;
      
          private void OnTriggerEnter(Collider other)
          {
              if (other.gameObject.layer == CAMPFIRE_LAYER)
                  StopCoroutine(_countDown);
          }
      
          private void OnTriggerExit(Collider other)
          {
              if (other.gameObject.layer == CAMPFIRE_LAYER)
                  _countDown = StartCoroutine(CountDown());
          }
      
          IEnumerator CountDown()
          {
              yield return COUNT_DOWN;
      
              Destroy(gameObject);
          }
      }
    • IEnumerator

      public class Example : MonoBehaviour {
          private IEnumerator coroutine;
      
          void Start()
          {
              coroutine = TestCoroutine();
      
              // 동작x
              StartCoroutine(TestCoroutine());
              StopCoroutine(TestCoroutine());
      
              // 동작o
              StartCoroutine(coroutine);
              StopCoroutine(coroutine);
          }
      
          IEnumerator TestCoroutine()
          {
              yield return new WaitForSeconds(2f);
              Debug.Log("테스트");
          }
      }

참고 자료

  1. 코루틴 중단하는 모든 방법 정리 (StopCoroutine)

  2. 코루틴(Coroutine) 중단하기

  3. MSDN : IEnumerator 인터페이스 (System.Collections)

  4. [UnityDocs : MonoBehaviour.StopCoroutine]

0개의 댓글