Created
October 7, 2024 18:46
-
-
Save SorraTheOrc/7b21a63cd38c5845a8d1ecc653bba04a to your computer and use it in GitHub Desktop.
Coroutine helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
/// <summary> | |
/// A helper class to start coroutines from non-MonoBehaviour classes. | |
/// | |
/// Usage: | |
/// To start a coroutine from a non-MonoBehaviour class, call CoroutineHelper.Instance.StartHelperCoroutine(yourCoroutine). | |
/// Example: | |
/// IEnumerator YourCoroutine() | |
/// { | |
/// // Your coroutine logic here | |
/// yield return null; | |
/// } | |
/// | |
/// CoroutineHelper.Instance.StartHelperCoroutine(YourCoroutine()); | |
/// </summary> | |
public class CoroutineHelper : MonoBehaviour | |
{ | |
private static CoroutineHelper _instance; | |
/// <summary> | |
/// Gets the singleton instance of the CoroutineHelper. | |
/// If it doesn't exist, it creates a new GameObject and attaches this component to it. | |
/// </summary> | |
public static CoroutineHelper Instance | |
{ | |
get | |
{ | |
if (_instance == null) | |
{ | |
GameObject obj = new GameObject("CoroutineHelper"); | |
_instance = obj.AddComponent<CoroutineHelper>(); | |
DontDestroyOnLoad(obj); | |
} | |
return _instance; | |
} | |
} | |
/// <summary> | |
/// Starts a coroutine using the singleton instance of CoroutineHelper. | |
/// </summary> | |
/// <param name="coroutine">The coroutine to start.</param> | |
public void StartHelperCoroutine(IEnumerator coroutine) | |
{ | |
StartCoroutine(coroutine); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment