Unity - CoroutineExecutor

Simple class for executing Coroutine easily


using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;



public class CoroutineExecutor : MonoBehaviour
{

    public System.Action DoneCallback;
<!-- more -->


    void Start()
    {
        DontDestroyOnLoad(transform.gameObject);
    }


    void Do(AsyncOperation ao, System.Action callback)
    {
        DoneCallback = callback;
        StartCoroutine(_WaitForDone(ao));
    }

    IEnumerator _WaitForDone(AsyncOperation ao)
    {
        if (ao != null)
        {
            while (!ao.isDone)
                yield return null;
        }

        if (DoneCallback != null)
            DoneCallback();

        Destroy(this.gameObject);

        yield return 0;
    }

 
    void Do(IEnumerator routine, System.Action callback)
    {
        DoneCallback = callback;
        StartCoroutine(_WaitForDone(routine));
    }
    IEnumerator _WaitForDone(IEnumerator routine)
    {
        if (routine != null)
        {
            yield return routine;
        }

        if (DoneCallback != null)
            DoneCallback();

        Destroy(this.gameObject);

        yield return 0;
    }

 
    public static void Create(AsyncOperation ao, System.Action callback)
    {
        GameObject go = new GameObject();
        CoroutineExecutor executor = go.AddComponent<CoroutineExecutor>();
        if (executor != null)
        {
            executor.Do(ao, callback);
        }
    }

 
    public static void Create(IEnumerator routine, System.Action callback)
    {
        GameObject go = new GameObject();
        CoroutineExecutor executor = go.AddComponent<CoroutineExecutor>();
        if (executor != null)
        {
            executor.Do(routine, callback);
        }
    }
}



WRITTEN BY:    Suntabu