1

Is there a way to have a variable point to one of a number of coroutines in C# in Unity3D?

public class Example : MonoBehaviour
{
    ? something ?  crt;

    private IEnumerator CoroutineA()
    {
    }

    private IEnumerator CoroutineB()
    {
    }

    void Start()
    {
        crt = CoroutineA;
        StartCoroutine(crt);
    }
}
Fattie
  • 27,874
  • 70
  • 431
  • 719
  • "Recall that Unity has a particular situation with `Func` and `Action`" What should I be recalling? – 31eee384 Dec 31 '15 at 18:22

2 Answers2

4

The type that you are looking for is a delegate. Delegates are similar to function pointers, and are not specific to Unity3D.

public class Example : MonoBehaviour
{
    private delegate IEnumerator CoroutineDelegate();

    private IEnumerator CoroutineA()
    {
    }

    private IEnumerator CoroutineB()
    {
    }

    public void Start()
    {
        CoroutineDelegate crt = CoroutineA;
        StartCoroutine(crt());
    }
}
Fattie
  • 27,874
  • 70
  • 431
  • 719
Brett Wolfington
  • 6,587
  • 4
  • 32
  • 51
0

Simply, use the fact that StartCoroutine function just needs an IEnumerator object to start the corresponding coroutine.

This means that you can create variables of type IEnumerator and assign your coroutines' return values to them (Recall that a coroutine is indeed a generator, i.e. returns IEnumerator).

Then, just call StartCoroutine on the variable. In your example, the field crt should have type IEnumerator. And in your Start method, you should assign to it like this:

crt = CoroutineA();

Then if you wanted to start its assigned coroutine, do it like this:

StartCoroutine (crt);
Joman68
  • 2,248
  • 3
  • 34
  • 36
M.Mahdi
  • 1
  • 2