Engine/Unity

[TIL] MonoBehaviour.StopCoroutine() 주의사항 한 가지

VirtualDever 2022. 3. 22. 20:27

당연한 것일 수도 있겠지만 비활성화된 (Disabled) 게임 오브젝트에는 StopCoroutine()이 안 먹힙니다. 만약 코루틴을 시작하거나 정지할 때 해당 게임오브젝트가 비활성화 되어 있다면 에러가 발생합니다.

 

using UnityEngine; using System.Collections;

public class Example : MonoBehaviour { // keep a copy of the executing script private IEnumerator coroutine;

// Use this for initialization
void Start()
{
    print("Starting " + Time.time);
    coroutine = WaitAndPrint(3.0f);
    StartCoroutine(coroutine);
    print("Done " + Time.time);
}

// print to the console every 3 seconds.
// yield is causing WaitAndPrint to pause every 3 seconds
public IEnumerator WaitAndPrint(float waitTime)
{
    while (true)
    {
        yield return new WaitForSeconds(waitTime);
        print("WaitAndPrint " + Time.time);
    }
}

void Update()
{
    if (Input.GetKeyDown("space"))
    {
        StopCoroutine(coroutine);
        print("Stopped " + Time.time);
    }
}
}

출처 - https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html

 

Unity - Scripting API: MonoBehaviour.StopCoroutine

Success! Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable. Close

docs.unity3d.com