I have a coroutine that uses a list. Here is the general structure of my code:
IEnumerator Collect(){
while(running){
if(list.Count> 0)
DoSomething()
yield return new WaitForSeconds (3);
RemoveItemFromList() //<-- this will cause the coroutine to stop.
}
}
List<T> tempList = new List<T>;
void DoSomething(){
tempList = list;
foreach(Item item in tempList)
DoSomethingElse();
}
What I am confused about is this: I have another method that is not called in the above coroutine that will add or remove an item from the list. This works fine and the coroutine will continue to work with the changes made to the list, even while the coroutine is running. What doesn’t work is if I try to add or remove an item in the list using a method called inside the coroutine. This breaks the coroutine by preventing it from continuing to run. Any thoughts about this?
There are several things that do not make much sense in your code. First of all your coroutine does not yield inside the while loop, at least in the code you’ve posted. If you do not yield inside your while loop you will get stuck in that while loop until running turns false.
The second thing is what is the point of “tempList”? You do not create a temporary list as you just store the same list reference in another variable. So instead of
tempList = list;
foreach(Item item in tempList)
you could simply do
foreach(Item item in list)
as there’s no difference. If you actually wanted to create a temporary copy of the list you have to create a new list:
tempList = new List<Item>(list);
foreach(Item item in tempList)
Since your code doesn’t seem to be your actual code it’s hard to actually understand your problem. The sentence:
This breaks the coroutine
could mean anything. Where exactly do you add / remove elements? You can not add or remove elements while iterating through a list using a foreach loop. The enumerator that is used by the foreach loop will be invalidated when the list is changed.