- Home /
How to store coroutines inside a List?
I want to create a List of coroutines to start if future. How to store such functions inside a list?
Say we have a function like:
IEnumerator Example() {
while (true) {
yield return new WaitForFixedUpdate();
}
}
We cant store it inside something like `List> list` but we get compiler error like:
Error 1 The best overloaded method match for 'System.Collections.Generic.List<System.Func<System.Collections.IEnumerator>>.Add(System.Func<System.Collections.IEnumerator>)' has some invalid arguments
when we call
list.Add(Example);
or if we use `List list` we get no compile errors but on
if (disposeActions.Any()) {
yield return StartCoroutine(list[0]); //here we get null exception
disposeActions.RemoveAt(0);
}
So I wonder how to create a list to store IEnumerator functions and be capable to send its items to coutines?
Read up on delegates: http://msdn.microsoft.com/en-us/library/ms173171(v=vs.80).aspx
You can use delegates to hold a reference to a method. That method can contain your coroutine code and the delegates can go into a list. *Haven't done exactly this before but makes sense to me at a glance at least.
Coroutines are not exaclty methods since the compiler generate an anonymous class, so I'm not sure you can call them using delegates.
You could create a method corresponding to each coroutine that call StartCoroutine. But that sounds a bit heavy.
@$$anonymous$$ryptos: the point is to `yield return StartCorutine(function)` s from that list one by one (so to say destroy only one asset bundle at a time)
Answer by Paulo-Henrique025 · Aug 17, 2012 at 07:37 PM
Store strings!
public List<String> coroutinesList = new List<String>();
void CallStoredRoutine(int index)
{
StartCoroutine(coroutineList[index]);
}
Answer by MaDDoX · Jan 19, 2017 at 04:44 AM
Did you try this?
List<Func<IEnumerator>> coroutines;
When iterating, make sure to check the element for null before invoking the coroutine.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Flip over an object (smooth transition) 3 Answers
StreamWriter issue c# 0 Answers