Biswadeep Sarkar's answer is pretty good. I improved it a bit. Made a universal function for waiting for parallel coroutines. Feel free to use and further modify it.
IEnumerator WaitForSomeCoroutines(params IEnumerator[] ienumerators)
{
Debug.Log($"Start time of parallel routines: {Time.time}");
if (ienumerators != null & ienumerators.Length > 0)
{
Coroutine[] coroutines = new Coroutine[ienumerators.Length];
for (int i = 0; i < ienumerators.Length; i++)
coroutines[i] = StartCoroutine(ienumerators[i]);
for (int i = 0; i < coroutines.Length; i++)
yield return coroutines[i];
}
else
yield return null;
Debug.Log($"End time of parallel routines: {Time.time}");
}
So, imagine you have some routines:
IEnumerator A(float time) { yield return new WaitForSeconds(time); }
IEnumerator B(float time) { yield return new WaitForSeconds(time); }
IEnumerator C(float time) { yield return new WaitForSeconds(time); }
You want routine D waits for complete of routines A,B and C. You do:
IEnumerator D()
{
// We wait until 3 other coroutines are finished.
yield return StartCoroutine(WaitForSomeCoroutines(
A(1f),
B(3f),
C(2f)));
// Now we make our stuff.
Debug.Log("Working on my stuff...");
}
yield StartCoroutine(a())
waits a coroutine to finish, but I want to start all of them at the same time, to execute in parallel. Each one has its own duration, and when the last of them end,d
should print "all over". – Colleyvoid
function) a lot ofStartCoroutine(a())
,StartCoroutine(b())
, etc., all of them will execute in parallel. Btw I'm thinking about having anint
counting the number of ended coroutines, where all of them increase this int when over. – Colleyyield
works. If you put a log line between each of yourStartCoroutine
lines and a log at the top of botha
andb
, you'll find thata
runs first (all the way to the first yield), thenb
(all the way to the first yield). Feel free to attach a debugger, too. – Anaplasty