Unity コルーチンについての質問
Q&A
Closed
解決したいこと
Unityで、コルーチンについて分からないことがあり、質問をしたいです。
該当するソースコード
using System.Collections;
using UnityEngine;
public class CoroutineSample : MonoBehaviour
{
private Coroutine coroutine;
void Start()
{
coroutine = StartCoroutine(SampleA());
}
private IEnumerator SampleA()
{
yield return SampleB();
if (coroutine != null) Debug.Log("Bad");
if (coroutine == null) Debug.Log("Good");
}
private IEnumerator SampleB()
{
coroutine = null;
Debug.Log("null");
yield return null;
}
}
これを実行してみたところ、下の画像のように
Debug.Log("null");
Debug.Log("Bad");
の順でコンソールに表示されました。
先にcoroutine = null;になっているのなら、
if (coroutine == null) Debug.Log("Good");の方が表示されると思ったのですが、違いました。
なぜこのような結果になるのか質問をしたいです。
自分で試したこと
private IEnumerator SampleB()
{
yield return null;
coroutine = null;
Debug.Log("null");
yield return null;
}
このように、 SampleB()において、coroutine = null;の前に
yield return null;やyield return new WaitForSeconds(1f);
などの間を挟むと、
Debug.Log("Good");の方が表示されるようになりましたが、
それもなぜなのかよく分かりません。
