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);
}
}
@TJHeuvel
Copy link

Ouch, i wouldnt create a new Gameobject every time. Just use the current?

@berndsalewski
Copy link

berndsalewski commented Jun 20, 2017

@TJHeuvel the current GameObject is non-static, you cannot use it in a static context.
@LotteMakesStuff thanks for sharing

@Mecze
Copy link

Mecze commented Jun 20, 2017

@grosserZampano @TJHeuvel
Yes you can, just cache it on a static variable upon creating the object: it is called "Singleton". Next time if that static variable isn't null, you use the already created object. Also you don't need to monitor the courutine for destroying the object. It is more efficient

@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