Created
July 20, 2020 19:13
-
-
Save andrew-raphael-lukasik/1e30d92c7e0518a2883396e554745121 to your computer and use it in GitHub Desktop.
This file contains 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 System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class CoroutineController : MonoBehaviour | |
{ | |
static CoroutineController _singleton; | |
static Dictionary<string,IEnumerator> _routines = new Dictionary<string,IEnumerator>(100); | |
[RuntimeInitializeOnLoadMethod( RuntimeInitializeLoadType.BeforeSceneLoad )] | |
static void InitializeType () | |
{ | |
_singleton = new GameObject($"#{nameof(CoroutineController)}").AddComponent<CoroutineController>(); | |
DontDestroyOnLoad( _singleton ); | |
} | |
public static Coroutine Start ( IEnumerator routine ) => _singleton.StartCoroutine( routine ); | |
public static Coroutine Start ( IEnumerator routine , string id ) | |
{ | |
var coroutine = _singleton.StartCoroutine( routine ); | |
if( !_routines.ContainsKey(id) ) _routines.Add( id , routine ); | |
else | |
{ | |
_singleton.StopCoroutine( _routines[id] ); | |
_routines[id] = routine; | |
} | |
return coroutine; | |
} | |
public static void Stop ( IEnumerator routine ) => _singleton.StopCoroutine( routine ); | |
public static void Stop ( string id ) | |
{ | |
if( _routines.TryGetValue(id,out var routine) ) | |
{ | |
_singleton.StopCoroutine( routine ); | |
_routines.Remove( id ); | |
} | |
else Debug.LogWarning($"coroutine '{id}' not found"); | |
} | |
public static void StopAll () => _singleton.StopAllCoroutines(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment