0

I am trying to destroy monster when walking on it but each time I destroy it then i got this error:

InvalidOperationException: Collection was modified; enumeration operation may not execute. System.Collections.Generic.List`1+Enumerator[UnityEngine.GameObject].VerifyState () (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:778)

TimeMap.MoveSelectedUnitTo (Int32 x, Int32 y) (at Assets/TimeMap.cs:148)

foreach(GameObject thisMonster in monsterList) { if(thisMonster.GetComponent<Monsters>().tileX == selectedUnit.GetComponent<Unit>().tileX && thisMonster.GetComponent<Monsters>().tileY == selectedUnit.GetComponent<Unit>().tileY) { CarryMonster(thisMonster); counter++; } }

I am still trying to figure out what is wrong with this. The list certainly is not empty. I put monsters there every 5 moves.

chazefate
  • 822
  • 4
  • 13
  • 35
  • You can't remove items from a list that you are enumerating. This means that your CarryMonster is trying to remove the reference passed and this is not allowed – Steve Oct 23 '17 at 15:50
  • what kind of duplicate? Does it mean that I can use foreach only once? – chazefate Oct 23 '17 at 15:51
  • No you can't delete items you are enumerating though with a foreach loop. Change it to a for loop. – Sam Marion Oct 23 '17 at 15:52
  • Okay, I will try that. Thank you! Can you help me how to write thisMonster.GetComponent().tileX in for loop? I get to here: monsterList[i].tileX but I got error: error CS1061: Type `UnityEngine.GameObject' does not contain a definition for `tileX' – chazefate Oct 23 '17 at 15:53
  • Don't forget to inverse the loop. If you don't you're going to mess up the index as you delete. Take a look at this post. https://stackoverflow.com/questions/1582285/how-to-remove-elements-from-a-generic-list-while-iterating-over-it – Sam Marion Oct 23 '17 at 15:57
  • 1
    Use a normal for loop, depending on the type of the list. You can get the element at a given index with the indexer `[index]` method if it is a `List`. You can also simply use the `ElementAt` extension method in `System.Linq`. Remember to use `monsterList[i].GetComponent().TileX` – staa99 Oct 23 '17 at 16:14

0 Answers0