0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

コルーチンをUpdate内で呼んだ場合の挙動

Posted at

なんとなく理解しにくいので嫌だったコルーチンを調べてみた。

yield return null;
↑で,次のフレームで続きから処理が始まる。
それならUpdateで連続で呼ぶとどうなるんだ?と思って以下のサンプルを作成。

sample.cs
	void Update () {
		Debug.Log("Update:" );
		StartCoroutine("Sample");
		//アップデートの中で呼ぶと危険
	}

	private IEnumerator Sample(){
		int i = 0;

		Debug.Log("yield:"+ i + ":" + 1);
		yield return null;
		i++;

		Debug.Log("yield:"+ i + ":" + 2);
		yield return null;
		i++;

		Debug.Log("yield:"+ i + ":" + 3);
		yield return null;
		i++;

		Debug.Log("yield:"+ i + ":" + 4);
		yield return null;
		i++;

		Debug.Log("yield:"+ i + ":" + 5);
		yield return null;
		i++;

	}

結果

Main2_unity_-_update_lateupdate_timing_-_PC__Mac___Linux_Standalone__Personal___OpenGL_4_1_.png

結果を見ると,まぁそっか(他の人が書いている通りだよね)となった。

  • 1フレーム目
    Updateが実行されて,その中で
    コルーチン(001と命名)が実行されて, yield:0:1 を出力

  • 2フレーム目
    Updateが実行されて,その中で
    新しいコルーチン(002と命名)が実行されて, yield:0:1 を出力
    次に,001のコルーチンの続きが実行されて yield:1:2 を出力

以降これのループになる。

気づいたこと

  • 新しいコルーチン処理ほど先に実行される
    • だからきれいな順番で値が出力されている
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?