Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Resolved Hitbox issue

Discussion in 'Scripting' started by jeffreyjene, Dec 21, 2020.

  1. jeffreyjene

    jeffreyjene

    Joined:
    Jul 9, 2018
    Posts:
    14
    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?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,780
    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:

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

    jeffreyjene

    Joined:
    Jul 9, 2018
    Posts:
    14
    Resolved. I added a OnTriggerStay() in the hitbox that destroys enemies with 0 health while in the hitbox collider.