2
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 3 years have passed since last update.

Unity Coroutineを入れ子にした時の実行順

Posted at

##0.0 はじめに
Coroutine(コルーチン)は実行時間などを制御するためにとても便利な関数ですが、入れ子にした時に(コルーチンの中でコルーチンを呼んだ時に)期待通りの動きにならず少し手間取りました。解決策は単純ですが、ここに備忘録として記載しておきます。

##1.0 期待した動作
コルーチンMainCo()の途中でSubCo()を呼び出し、SubCo()が完了した後、残りのMainCo()を実行する。

期待した出力:
メインは 0 回目です
サブは 0 回目です
サブは 1 回目です
サブは 2 回目です
メインは 1 回目です
サブは 0 回目です
サブは 1 回目です
サブは 2 回目です
メインは 2 回目です
サブは 0 回目です
サブは 1 回目です
サブは 2 回目です

2.0 正しいコード

yield returnでサブコルーチンを呼び出す。
(実行順が目で追えるように1秒待機しています。)

CoroutineTest.cs
private void Start() {
    StartCoroutine(MainCo()); // MainCo関数を呼び出し
}

// メインのコルーチン
IEnumerator MainCo() {
    for (int i = 0; i < 3; i++) {
        Debug.Log($"メインは {i} 回目です");
        yield return StartCoroutine(SubCo()); // サブコルーチンを呼び出す
        yield return new WaitForSeconds(1.0f);
    }
}

// サブのコルーチン
IEnumerator SubCo() {
    for (int i = 0; i < 3; i++) {
        Debug.Log($"サブは {i} 回目です");
        yield return new WaitForSeconds(1.0f);
    }
}

3.0 間違ったコード

サブコルーチンを呼び出す際にyield returnがないためメインが止まらずサブと並行して動作している。

CoroutineTest.cs
private void Start() {
    StartCoroutine(MainCo()); // MainCo関数を呼び出し
}

// メインのコルーチン
IEnumerator MainCo() {
    for (int i = 0; i < 3; i++) {
        Debug.Log($"メインは {i} 回目です");
        StartCoroutine(SubCo()); // <--ここの部分 
        yield return new WaitForSeconds(1.0f);
    }
}

// サブのコルーチン
IEnumerator SubCo() {
    for (int i = 0; i < 3; i++) {
        Debug.Log($"サブは {i} 回目です");
        yield return new WaitForSeconds(1.0f);
    }
}
2
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
2
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?