I am getting the "collection was modified" error in my foreach loop, and the "object reference" error in my forloops. I understand both errors. The collection error is fired whenever a list is modified inside a foreach loop and the objectect reference error is fired when you try to access a property or method of a null object. I understand that. The problem is that no where in the foreach loop do I ever modify the collection or remove/add from it.
In the below example, enemy array would be a List<Enemy>. So basically my code would look like this inside my GotMessage function:
- Code: Select all
case "damageEnemy":
foreach(Enemy _enemy in enemy_array){ //this lines throws the error
_enemy.health -= 10;
}
break;
But for some reason I am getting an error with that telling me that that the collection was modified. The only time I ever remove or add to the enemy_array is NOT inside the foreach loop, its inside my main game loop. So how is it possible for these things to be going null or getting removed mid-iteration? Are the GotMessage and game loops executing simultaneously?
I've learned most of my programming from AS3, so I am pretty unfamiliar with multi-threading. Is it possible that the lists/arrays are getting edited elsewhere during the iteration by another thread? I've saw on google that I can use an expression called "lock" to try and prevent this. I just thought I'd get some feedback here first, as I've always been lost as to why I get this error in these places.