using System.Collections; using UnityEngine; public class StaticCoroutine : MonoBehaviour { static StaticCoroutine _instance; public static StaticCoroutine Instance { get { if(_instance == null) { Debug.Log("No Static Coroutine Instance"); } return _instance; } } // OnDestroy is called when the MonoBehaviour will be destroyed. // Coroutines are not stopped when a MonoBehaviour is disabled, but only when it is definitely destroyed. private void OnDestroy() { Instance?.StopAllCoroutines(); } // OnApplicationQuit is called on all game objects before the application is closed. // In the editor it is called when the user stops playmode. private void OnApplicationQuit() { Instance?.StopAllCoroutines(); } // Build will attempt to retrieve the class-wide instance, returning it when available. // If no instance exists, attempt to find another StaticCoroutine that exists. // If no StaticCoroutines are present, create a dedicated StaticCoroutine object. private void Awake() { if (_instance == null) { _instance = this; return; } Destroy(this.gameObject); } // Overloaded Static Coroutine Methods which use Unity's default Coroutines. // Polymorphism applied for best compatibility with the standard engine. public static void Start(string methodName) { Instance?.StartCoroutine(methodName); } public static void Start(string methodName, object value) { Instance?.StartCoroutine(methodName, value); } public static void Start(IEnumerator routine) { Instance?.StartCoroutine(routine); } public static void Stop(IEnumerator routine) { Instance?.StopCoroutine(routine); } }