LoginSignup
28
18

More than 5 years have passed since last update.

MonoBehaviourを継承していないクラスでStartCoroutineを使う

Posted at

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();
    }
}

28
18
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
28
18