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("테스트");
}
}
[UnityDocs : MonoBehaviour.StopCoroutine]