Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by Deadcow_ · Mar 11, 2014 at 08:31 PM · coroutinecoroutines

Wait bunch of coroutines inside of coroutine

Okay, in a simple scenario when you need to wait coroutine inside coroutine you just call this:

 yield return StartCoroutine(obj.MyAction());
 // do something

But when I need to start MyAction for a bunch of objects and wait until them all will be finished? Is there a simple way, or I need to use additional variables and check it in loop within parent coroutine? I mean, do something like this:

 foreach (MyScript s in scriptsToRun)
 {
     StartCoroutine(s.MyAction());
 }
 bool isActionsProcessed = false;
 while (!isActionsProcessed)
 {
     isActionsProcessed = true;
     foreach (MyScript s in scriptsToRun)
     {
         if (!s.IsActionProcessed)
             isActionsProcessed = false;
     }
     if (!isActionsProcessed) yield return null;
 }
 // do something
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by whydoidoit · Mar 12, 2014 at 07:26 AM

You could pass a class parameter to the coroutine that contains a count of currently running routines or you could make a generic coroutine runner that does that if you prefer.

ParallelSupport.cs

  using System.Collections;
  using UnityEngine;


  public class RunInfo {
       public int count;
       public static Dictionary<string, RunInfo> runners = new Dictionary<string, RunInfo>();
  }

  public class ParallelSupport : MonoBehaviour { 
        public static ParallelSupport instance;
        void Awake() { instance = this; }
  }

  public static class ParallelCoroutineExt {

    public static RunInfo ParallelCoroutine(this IEnumerator coroutine, string group = "default") {
         if(!RunInfo.runners.ContainsKey(group)) {
              RunInfo.runners[group] = new RunInfo();
         }
         var ri = RunInfo.runners[group];
         ri.count++;
         ParallelSupport.instance.StartCoroutine(DoParallel(coroutine, ri));
         return ri;
     }

     static IEnumerator DoParallel(IEnumerator coroutine, RunInfo ri) {
       yield return ParallelSupport.instance.StartCoroutine(coroutine);
       ri.count--;
     } 
 }

You then attach ParallelSupport to anything in your scene that will hang around and then you can do this:

 RunInfo info;


 foreach (MyScript s in scriptsToRun)
 {
     info = s.MyAction().ParallelCoroutine(); //Optionally specify a group here
 }

 while(info.count > 0) yield return null;
Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image whydoidoit · Mar 12, 2014 at 07:28 AM 0
Share

Note that this coroutine is running based on the lifetime and activation of what you attached ParallelSupport to - it would be easy to adapt to pass a behaviour on which it should be run ins$$anonymous$$d.

avatar image Deadcow_ · Mar 16, 2014 at 04:09 PM 0
Share

Thanks a lot, this pattern works great

avatar image
2

Answer by beck · Mar 12, 2014 at 06:04 AM

If you are not using the Unity's special yields (WaitForSeconds, StartCoroutine) from the coroutines you're waiting for, you can use the IEnumerator object itself:

 IEnumerator routine1 = SomeCoroutine();
 IEnumerator routine2 = SomeOtherCoroutine();
 
 while(routine1.MoveNext() | routine2.MoveNext())
 {
     yield return null;
 }

The above code reads "while routine1 or routine2 are not finished, wait for 1 frame"

Comment
Add comment · Show 6 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Deadcow_ · Mar 13, 2014 at 08:12 PM 0
Share

Wow, manually iterate coroutine is gotta be obvious since they returned IEnumerator, but I've never thought of them that way. I changed code a bit to work with collection of coroutines, but it looks like this code not work properly, maybe you can help me to figure out why.

 // Collection of coroutines
 IEnumerator[] waitToDestroy = GetBunchofCoroutines();
 
 bool destroyFinished = false;
 while (!destroyFinished)
 {
     destroyFinished = true;
 
     Array.ForEach(waitToDestroy, cor => { if (cor.$$anonymous$$oveNext()) destroyFinished = false; });
 
     if (!destroyFinished) yield return null;
 }

 // do something

(btw now I see that I can use array ins$$anonymous$$d of list)

Coroutines work fine, but this last "do something" part starts right after calling coroutines, not after finishing them.

avatar image whydoidoit · Mar 13, 2014 at 09:55 PM 0
Share

Actually @beck's code does not iterate the two routines in parallel it does one then the other due to the way that if evaluates its terms.

Your code looks like it just does the whole thing at once.

avatar image beck · Mar 13, 2014 at 11:06 PM 0
Share

Yes sorry, my while should have read:

while(routine1.$$anonymous$$oveNext() | routine2.$$anonymous$$oveNext())

Corrected my post.

avatar image Deadcow_ · Mar 15, 2014 at 04:54 PM 0
Share

Okay, I'd cleaned my code a bit but still can't understand why it not working properly. @whydoidoit, why it is does whole thing at once? As for me this scenario looks proper, seems like I missed something. It calls $$anonymous$$oveNext on the each coroutine and waits till the next frame if there is any coroutines that can iterate. I beleive I missed something obvious, but I cannot figure out what

avatar image whydoidoit · Mar 15, 2014 at 05:26 PM 0
Share

So it would depend on whether those coroutines did anything apart from yield return null; I would seriously consider using my answer below...

Show more comments
avatar image
2

Answer by Ash-Blue · Mar 23, 2019 at 07:39 PM

Actually you can do this with just a few simple lines. You need to return each coroutine in a loop and it will automatically complete when it has nothing left to do. Here is an example that will wait for a list of coroutines to complete.

 private IEnumerator WaitForMultipleCoroutines (List<Coroutine> coroutines) {
   var animations = new Stack(coroutines);
   while (animations.Count > 0) {
     var animation = animations.Pop();
     yield return animation ;
   }

   // Logic to trigger after all coroutines complete goes here
 }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image dithyrambs · Jul 24, 2020 at 04:27 AM 0
Share

Worked great! Underrated answer.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

24 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Nested Coroutines: last coroutine quits early 1 Answer

I need to Stop and Restart a Co-Routine at anytime 1 Answer

coroutine not running after yield new WaitForSeconds 1 Answer

How to properly implement a constant queue of actions in the background,How to properly implement a continuous background queue of actions? 1 Answer

Why doesn't a coroutine start executing from beginning when I start it again? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges