Last active
July 31, 2020 22:35
-
-
Save willis81808/90e1698046b96cf85b5839e70b9e8e8c to your computer and use it in GitHub Desktop.
A Useful Extension of the Built-In Unity Coroutines.
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 System.Collections; | |
| using System.Collections.Generic; | |
| using UnityEngine; | |
| public class CoroutineManager : MonoBehaviour | |
| { | |
| private static CoroutineManager _instance; | |
| private static CoroutineManager Instance | |
| { | |
| get | |
| { | |
| if (_instance == null) | |
| { | |
| _instance = new GameObject("Coroutine Manager").AddComponent<CoroutineManager>(); | |
| DontDestroyOnLoad(_instance.gameObject); | |
| } | |
| return _instance; | |
| } | |
| } | |
| private struct ActionData | |
| { | |
| public IEnumerator coroutine; | |
| public bool running; | |
| } | |
| private static Dictionary<string, ActionData> map = new Dictionary<string, ActionData>(); | |
| public static Coroutine Start(string key, IEnumerator action, bool replaceExisting = false) | |
| { | |
| if (map.ContainsKey(key)) | |
| { | |
| if (replaceExisting || !map[key].running) | |
| { | |
| Stop(key); | |
| map.Remove(key); | |
| } | |
| else | |
| { | |
| return null; | |
| } | |
| } | |
| var newData = new ActionData(); | |
| newData.coroutine = action; | |
| map.Add(key, newData); | |
| return Instance.StartCoroutine(Execute(key, action)); | |
| } | |
| private static IEnumerator Execute(string key, IEnumerator action) | |
| { | |
| var data = map[key]; | |
| data.running = true; | |
| map[key] = data; | |
| yield return action; | |
| data.running = false; | |
| map[key] = data; | |
| } | |
| public static bool IsRunning(string key) | |
| { | |
| if (!map.ContainsKey(key)) | |
| { | |
| return false; | |
| } | |
| return map[key].running; | |
| } | |
| public static bool Stop(string key) | |
| { | |
| if (!map.ContainsKey(key)) | |
| { | |
| return false; | |
| } | |
| Instance.StopCoroutine(map[key].coroutine); | |
| map.Remove(key); | |
| return true; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment