LoginSignup
75
80

More than 5 years have passed since last update.

コルーチンについて

Last updated at Posted at 2014-03-08

シングルスレッド環境でマルチスレッドっぽく動作できる
コルーチンについての理解度が低かったので挙動を確認してみた

コルーチンの特徴

コルーチンについては、通常の関数のとは異なり、
処理を途中で抜けて任意のタイミングで中断部分から処理を再開することが特徴です。
yield return が呼び出されると、その時点で関数は処理を中断して制御を返します。
シングルスレッドの環境で擬似的にマルチスレッドを実現するための手段です。

使いどころ

遅延評価をする場合に使用するので、ゲームでは状態シーケンス管理になどに使えそう。
バトルに入る前では、フィールドオブジェクト生成 → バトル初期値設定 → プレイヤー、敵オブジェクトを生成
→ バトルシーントランザクション → バトル開始 みたいな感じで

UnityのStartCoroutineを使用しての動作確認

以下の実行結果より処理を途中で抜けて
任意のタイミングで中断部分から処理を再開していることがわかります

void Start () {
    StartCoroutine("Coroutine1");
}

void Update () {
    Debug.Log ("Update.");
}

public IEnumerator Coroutine1()
{
    Debug.Log("Start-1");
    Debug.Log("--------");
    yield return StartCoroutine("Coroutine2");
    Debug.Log("--------");
    Debug.Log("Start-2");
    yield return null;
    Debug.Log("Start-3");
}

private IEnumerator Coroutine2()
{
    Debug.Log("Nest-1");
    yield return null;

    Debug.Log("Nest-2");
    yield return null;

    Debug.Log("Nest-3");
}

// 実行結果
//
//   Start-1
//   --------
//   Nest-1
//   Update.
//   Update.
//   Nest-2
//   Update.
//   Nest-3
//   --------
//   Start-2
//   Update.
//   Start-3
//   Update.
//   Update.
//   :
//   :
75
80
1

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
75
80