Reputation: 12353
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);
}
}
Upvotes: 1
Views: 164
Reputation: 1
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);
Upvotes: 0
Reputation: 6627
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());
}
}
Upvotes: 4