Created
June 19, 2017 22:32
-
-
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
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 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 =)