-
-
Save LotteMakesStuff/d179d28f29bc9bb499dc5260e0146154 to your computer and use it in GitHub Desktop.
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 the current GameObject is non-static, you cannot use it in a static context.
@LotteMakesStuff thanks for sharing
@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
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 =)
Ouch, i wouldnt create a new Gameobject every time. Just use the current?