Hitbox issue

I have a hitbox in the form of a box collider trigger in front of my character. When an enemy with a health components enters it, they are added to a List of targets. When they exit the trigger, they are removed from the List. I also want to be able to remove enemies from the list that have reached zero health while in the collider (and on the List). If I try to do this directly: targets.Remove(enemy) - I get this error:

InvalidOperationException: Collection was modified; enumeration operation may not execute.

I’m not iterating over the target list myself, though I’m thinking that is being done in the OnTriggerEnter/Exit method.

Suggestions?

Well you have that method… is it iterating?

You can also use the .RemoveAll() method with a predicate that would remove dead enemies from the list. For instance, if you have a list of GameObjects called Foo and you want to remove GameObjects that were destroyed, you can call:

Foo.RemoveAll( x => !x);  // remove all that are "not true", i.e, have been destroyed

Resolved. I added a OnTriggerStay() in the hitbox that destroys enemies with 0 health while in the hitbox collider.