###### tags: `Unity` # 親CoroutineをStopCorutineで止めたとき子Coroutineも止まるのか検証 ## 検証コード ```csharp= 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を実行すると別物とされるため) ## 追記 これならうまくいく ```csharp= 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の罠 ```csharp= private IEnumerator A() { Debug.Log("startA"); yield return new WaitForSeconds(100); Debug.Log("endA"); } ``` 100秒待機中に停止・再開始すると、100秒は無視され即座に"endA"が出力される。 ```charp= 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"); } ``` 上も同様 ```charp= 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を実行すると止まる。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up