Unityの公式TutorialのEndless Runnerにありました.
using UnityEngine;
using System.Collections;
/// <summary>
/// This class allows us to start Coroutines from non-Monobehaviour scripts
/// Create a GameObject it will use to launch the coroutine on
/// </summary>
public class CoroutineHandler : MonoBehaviour
{
static protected CoroutineHandler m_Instance;
static public CoroutineHandler instance
{
get
{
if(m_Instance == null)
{
GameObject o = new GameObject("CoroutineHandler");
DontDestroyOnLoad(o);
m_Instance = o.AddComponent<CoroutineHandler>();
}
return m_Instance;
}
}
public void OnDisable()
{
if(m_Instance)
Destroy(m_Instance.gameObject);
}
static public Coroutine StartStaticCoroutine(IEnumerator coroutine)
{
return instance.StartCoroutine(coroutine);
}
}
サンプル
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// コルーチンを使うクラス
public class SampleClass
{
public void Test()
{
// 使い方の例
CoroutineHandler.StartStaticCoroutine(DebugCoroutine("test"));
}
// コルーチン
IEnumerator DebugCoroutine(string t)
{
yield return new WaitForSeconds(2f);
Debug.Log(t);
}
}
// 呼び出す用
public class CoroutineSample : MonoBehaviour
{
private void Start()
{
var sample = new SampleClass();
sample.Test();
}
}