LoginSignup
13
9

More than 5 years have passed since last update.

コルーチンを呼び出し元とは別のオブジェクトで動作させる方法

Last updated at Posted at 2015-12-14

Unityのコルーチンを使用したことがある前提です。

非アクティブなオブジェクト(仮にCallCoroutineObjectとする)にアタッチされたスクリプトから、
StartCoroutineを開始すると、以下のエラーが出ます。

Coroutine couldn't be started because the the game object 'CallCoroutineObject' is inactive!

また、StartCoroutineを開始しても、あとで非アクティブになるとコルーチンは実行されなくなります。
通常は上記の挙動で困るのであれば、設計を見直すべきですが、そんな事をしている時間が無いときもありますよね。

そこで以下のようにします。

using UnityEngine;
using System;
using System.Collections;

public class GlobalCoroutine : MonoBehaviour {

    public static void Go (IEnumerator coroutine) {
        GameObject obj = new GameObject ();     // コルーチン実行用オブジェクト作成
        obj.name = "GlobalCoroutine";

        GlobalCoroutine component = obj.AddComponent <GlobalCoroutine> ();
        if (component != null) {
            component.StartCoroutine (component.Do (coroutine));
        }
    }

    IEnumerator Do (IEnumerator src) {
        while (src.MoveNext ()) {               // コルーチンの終了を待つ
            yield return null;
        }

        Destroy (this.gameObject);              // コルーチン実行用オブジェクトを破棄
    }
}

呼び出し方
GlobalCoroutine.Go (MyCoroutine ());

これで親や自身のアクティブ状態に影響を受けずにコルーチンを動作させられます。

以上です。

13
9
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
13
9