Skip to content

Instantly share code, notes, and snippets.

@LotteMakesStuff
Created June 19, 2017 22:32
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LotteMakesStuff/d179d28f29bc9bb499dc5260e0146154 to your computer and use it in GitHub Desktop.
Save LotteMakesStuff/d179d28f29bc9bb499dc5260e0146154 to your computer and use it in GitHub Desktop.
Ever wanted to run a Unity Coroutine from game code thats not in a MonoBehaviour (for example, a static manager class). Now you can friends!! this class automates creating a dummy game object to run your coroutine and cleans itself up automagically when the routine has finished
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoroutineRunner : MonoBehaviour
{
public static void RunCoroutine(IEnumerator coroutine)
{
var go = new GameObject("runner");
DontDestroyOnLoad(go);
var runner = go.AddComponent<CoroutineRunner>();
runner.StartCoroutine(runner.MonitorRunning(coroutine));
}
IEnumerator MonitorRunning(IEnumerator coroutine)
{
while (coroutine.MoveNext())
{
yield return coroutine.Current;
}
Destroy(gameObject);
}
}
@Feacur
Copy link

Feacur commented Jul 25, 2017

Hey, it's kind of self-advertising, however check this out, please:
https://github.com/Feacur/UnityEngineStudy/blob/master/Assets/Plugins/Custom/Singleton/AutoInstanceMonoBehaviour.cs
You can use this auto instanced objects for static coroutines just as well.

I build stuff there from time to time, and you might find something useful.
Also thank you for these gists, I've found couple of useful scripts here, @LotteMakesStuff =)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment