以下のクラスを用意します。
CoroutineAccessor.cs
// UniRx 版に切り替える場合、この定義を有効化します //#define USING_UniRx using System.Collections; using UnityEngine; public class CoroutineAccessor : MonoBehaviour { #if !USING_UniRx /// <summary> /// GameObject アタッチなしで StartCoroutine を使うための instance /// </summary> static CoroutineAccessor Instance { get { if (instance == null) { GameObject obj = new GameObject(nameof(CoroutineAccessor)); DontDestroyOnLoad(obj); instance = obj.AddComponent<CoroutineAccessor>(); } return instance; } } static CoroutineAccessor instance; /// <summary> /// OnDisable /// </summary> void OnDisable() { if (instance != null) { Destroy(instance.gameObject); instance = null; } } #endif public static void Start(IEnumerator routine) { #if USING_UniRx UniRx.MainThreadDispatcher.StartCoroutine(routine); #else Instance.StartCoroutine(routine); #endif } }
呼び出しは以下の通り。
public static Call(int a, string b) { CoroutineAccessor.Start(method(a, b)); } static IEnumerator method(int a, string b) { yield return null; }