Skip to content

Instantly share code, notes, and snippets.

@willis81808
Last active July 31, 2020 22:35
Show Gist options
  • Select an option

  • Save willis81808/90e1698046b96cf85b5839e70b9e8e8c to your computer and use it in GitHub Desktop.

Select an option

Save willis81808/90e1698046b96cf85b5839e70b9e8e8c to your computer and use it in GitHub Desktop.
A Useful Extension of the Built-In Unity Coroutines.
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