Is it possible to pass coroutine's the way you would a function using a delegate?

Just as the title says.
I know that we can pass around functions with a delegate and make flexible code. I was just wondering if that is also possible for coroutines.

So the goal would be to have the coroutine passed around in something similar to a delegate (probably some sort of IEnumerator?) and then have that coroutine called with StartCoroutine or something similar without having to hard code the coroutine name in the StartCoroutine().

Thank you.

Yes, that’s possible. Though keep in mind that the actual “coroutine” is not a method but an object and that usually can only be used once to iterate through the statemachine that the compiler generated for your coroutine.

I would recommend reading through my coroutine crash course.

The actual “generator” method that returns an IEnumerator can be referred to by a delegate as usual since that’s just a normal method. Calling that method will create a new statemachine object that implements the IEnumerator interface.

If you have arguments for the coroutine that you want to encapsulate as well, you could use “IEnumerable” instead. That way the compiler generates another wrapper object that has the GetEnumerator() method to actually create a new instance which can be used in StartCoroutine.

System.Func<IEnumerator> someCoroutine;
// [ ... ]
someCoroutine = YourCoroutine;
// [ ... ]
StartCoroutine(someCoroutine());

When using IEnumerable, you can do something like that:

// note that this returns IEnumerable instead of IEnumerator
IEnumerable MyCoroutine(GameObject someParameter)
{
    // some fancy coroutine code
    yield return null;
}

Now we can simply use a variable, List or array of IEnumerable instances and use it like this:

List<IEnumerable> routines = new List<IEnumerable>();
// [ ... ]
routines.Add(MyCoroutine(someGoReference));
// [ ... ]
StartCoroutine(routines[0].GetEnumerator());

Though of course it’s possible to use a “normal” coroutine with a Func delegate that takes additional arguments as long as your coroutine definition matches the arguments

// normal coroutine, returns IEnumerator
IEnumerator MyCoroutine(GameObject someParameter)
{
    // some fancy coroutine code
    yield return null;
}
// [ ... ]
System.Func<GameObject, IEnumerator> someCoroutine;
// [ ... ]
someCoroutine = MyCoroutine;
// [ ... ]
StartCoroutine(someCoroutine(someGoReference));