Skip to content

Instantly share code, notes, and snippets.

@benui-dev
Created March 11, 2014 05:28
Show Gist options
  • Save benui-dev/9479979 to your computer and use it in GitHub Desktop.
Save benui-dev/9479979 to your computer and use it in GitHub Desktop.
Helper singleton for running multiple coroutines simultaneously, and then waiting for all of them to finish.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CoroutineSyncer : MonoBehaviour
{
static CoroutineSyncer m_instance;
public static CoroutineSyncer Instance
{
get
{
return m_instance;
}
}
int m_latestId = 0;
Dictionary<int, int> m_leftForID = new Dictionary<int, int>();
void Awake() {
m_instance = this;
}
public IEnumerator DoSimultaneously(List<IEnumerator> coroutines)
{
int localID = m_latestId++;
m_leftForID[localID] = coroutines.Count;
for (int i = 0; i < coroutines.Count; i++)
{
StartCoroutine(Wrapper(coroutines[i], localID));
}
while (m_leftForID[localID] > 0)
{
yield return null;
}
Debug.Log(localID+": Done all!");
}
IEnumerator Wrapper(IEnumerator coroutine, int id)
{
yield return StartCoroutine(coroutine);
OnComplete(id);
}
void OnComplete(int id)
{
Debug.Log(id + ": one is done");
m_leftForID[id] -= 1;
}
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CoroutineSyncerTest : MonoBehaviour {
void Start() {
var operations = new List<IEnumerator>();
for (int i = 0; i < 10; i++)
{
operations.Add(AsyncOperation(Random.Range(2f, 10f)));
}
StartCoroutine(CoroutineSyncer.Instance.DoSimultaneously(operations));
}
IEnumerator AsyncOperation(float time)
{
Debug.Log("Waiting for " + time);
yield return new WaitForSeconds(time);
Debug.Log("Done: " + time);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment