Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Storing Coroutines inside a list or variable in general?

Discussion in 'Scripting' started by elelec, Nov 15, 2015.

  1. elelec

    elelec

    Joined:
    Jul 21, 2014
    Posts:
    7
    I'm trying to store some IEnumarators inside non-Monobehaviour and non-static classes, which are taken from a static class, to be later accessed by a Monobehaviour class with the StartCoroutine function. If an instance of the non class gets its stored IEnumerator accessed, it will only successfully run one time and then completely skip the coroutine every other time. If two different instances are using the same coroutine, each will run once and then completely ignore all other tries. If the coroutine is accessed directly from the static class, it will run successfully.

    Well, this is pretty much the problem I've had, but I'd like to make the question more general. How does one use an IEnumerator as a variable (by making it equal to other existing IEnumerators)? Also, is there a better way to read an IEnumerator from another class?

    (I know I've written it in a confusing way, I'm sorry for that, but my head hurts from trying to figure this thing out and I can't exactly focus right now)
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,380
    The IEnumerator, or the function that generates the IEnumerator?

    Because once you start an IEnumerator generated by an iterator function, you can't reuse it.

    I'm willing to be you want to store a reference to the function that creates the IEnumerator used for the Coroutine. In which case you use delegates. In this case... you could just use the System.Func<IEnumerator> delegate.

    Code (csharp):
    1.  
    2. void Foo()
    3. {
    4.  
    5.     System.Func<IEnumerator> delegateRef = SomeRoutine;
    6.  
    7. }
    8.  
    9. IEnumerator SomeRoutine()
    10. {
    11.     //do your routine
    12. }
    13.  
    Then with that ref you could call StartCoroutine with it:

    Code (csharp):
    1.  
    2. StartCoroutine(delegateRef());
    3.  
     
    elelec likes this.
  3. elelec

    elelec

    Joined:
    Jul 21, 2014
    Posts:
    7
    It works perfectly! Thanks! It did take some tweaking around, but in the end it works! :D