Try   HackMD
tags: Unity

親CoroutineをStopCorutineで止めたとき子Coroutineも止まるのか検証

検証コード

private void Start() { _a = A(); StartCoroutine(_a); } private IEnumerator A() { Debug.Log("sA"); yield return StartCoroutine(B()); Debug.Log("eA"); } private IEnumerator B() { Debug.Log("sB"); yield return new WaitForSeconds(1); Debug.Log("eB"); } private void Update() { if (pause) { StopCoroutine(_a); } }

結果

そのまま実行した結果

sA
sB
eB
eB

Bが実行中にStopCoroutineを呼んだ場合

sA
sB
StopCoroutine(_a);
eB

まとめ

親コルーチンが止まっても子コルーチンは止まらない
(StartCoroutineを実行すると別物とされるため)

追記

これならうまくいく

private void Start() { _a = A(); StartCoroutine(_a); } private IEnumerator A() { Debug.Log("sA"); yield return B(); Debug.Log("eA"); } private IEnumerator B() { Debug.Log("sB"); yield return new WaitForSeconds(1); Debug.Log("eB"); } private void Update() { if (_pause) { StopCoroutine(_a); } }

StopCoroutineの罠

private IEnumerator A() { Debug.Log("startA"); yield return new WaitForSeconds(100); Debug.Log("endA"); }

100秒待機中に停止・再開始すると、100秒は無視され即座に"endA"が出力される。

private IEnumerator A() { Debug.Log("startA"); yield return B(); Debug.Log("endA"); } private IEnumerator B() { Debug.Log("startB"); yield return new WaitForSeconds(1); Debug.Log("endB"); }

上も同様

private IEnumerator A(INLCoroutineExecutor executor) { Debug.Log("startA"); yield return executor.Run(B); Debug.Log("endA"); } private IEnumerator B(INLCoroutineExecutor executor) { Debug.Log("startB"); yield return executor.Kill(); Debug.Log("endB"); }

内部から外部のStopCoroutineを実行すると止まると思いきや止まらない
外部からStopCoroutineを実行すると止まる。