Game/Unity
[Unity] 코루틴 중단하는 모든 방법 정리 (StopCoroutine)
kkkrrr
2019. 7. 15. 12:47
유니티에서 코루틴을 중단할 때 쓰이는 StopCoroutine은 제대로 작동하지 않는 경우가 많다.
그 이유는 StopCoroutine 메서드를 잘못 사용했기 때문이다.
StopCoroutine의 인자는 string, IEnumerator, Coroutine 의 세가지 타입을 받을 수 있으며, 어떤 인자를 사용하냐에 따라 그 사용법이 달라진다.
개인적으로 1번 방법은 추천하지 않으며 2번과 3번 중 편한 방법을 선택하는 것을 추천한다.
1. String
첫 번째는 가장 간단하게 String 즉, 코루틴의 이름을 인자로 사용하는 경우이다.
StartCoroutine과 StopCoroutine에 각각 코루틴의 이름을 String 형태로 입력하면 된다.
void Start()
{
StartMethod();
}
void Update(){
if (Input.GetKeyDown(KeyCode.Space))
{
StopMethod();
}
}
void StartMethod()
{
StartCoroutine("myCoroutine");
}
void StopMethod()
{
StopCoroutine("myCoroutine");
}
IEnumerator myCoroutine()
{
yield return null;
int count = 0;
while (true)
{
count ++;
Debug.Log(count);
yield return new WaitForSeconds(0.5f);
}
}
아주 간단하지만 잘 쓰지 않게 된다.
그 이유는 첫 번째로 String 형태이기에 parameter를 전달할 수 없기 때문이고,
두 번째로 코루틴 이름을 잘못 입력하더라도 컴파일 에러가 발생하지 않기 때문이다.
2. IEnumerator
두 번째는 IEnumerator 타입을 이용하는 방법이다.
IEnumerator 타입 변수를 선언하고 중단하고자 하는 코루틴을 담아 사용한다.
void Start()
{
StartMethod();
}
void Update(){
if (Input.GetKeyDown(KeyCode.Space))
{
StopMethod();
}
}
IEnumerator coroutine;
void StartMethod()
{
coroutine = myCoroutine();
StartCoroutine(coroutine);
}
void StopMethod()
{
if (coroutine != null)
{
StopCoroutine(coroutine);
}
}
IEnumerator myCoroutine()
{
yield return null;
int count = 0;
while (true)
{
count ++;
Debug.Log(count);
yield return new WaitForSeconds(0.5f);
}
}
3. Coroutine
마지막으로, Coroutine 타입 변수를 사용하는 방법이다.
2번 방법과는 다르게 StartCoroutine의 반환값을 변수에 담아 사용한다.
void Start()
{
StartMethod();
}
void Update(){
if (Input.GetKeyDown(KeyCode.Space))
{
StopMethod();
}
}
Coroutine coroutine;
void StartMethod()
{
coroutine = StartCoroutine(myCoroutine());
}
void StopMethod()
{
if (coroutine != null)
{
StopCoroutine(coroutine);
}
}
IEnumerator myCoroutine()
{
yield return null;
int count = 0;
while (true)
{
count ++;
Debug.Log(count);
yield return new WaitForSeconds(0.5f);
}
}
ref : https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html