How to remove a specific item from a list?

I have a list of knights, and some code that checks to see if a knight has lost all his health. If he has, the code should remove him from the list of knights. However, I get this error:

ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index

Any help would be appreciated :slight_smile:

Here’s the code:

public void CheckHealth()

{
	for(int i = knightsList.Count; i > 0; i-- )
	{
		if (knightsList*.health <= 0)*
  •   	{*
    

_ knightsList.Remove(knightsList*);_
_
}_
_
}_
_
}*_

Well your first i value will be bigger than the knights list.

Lets say your list count is 10, this means it contains index values of 0 through 9. So when you begin your loop your i value is 10, but trying to get index 10 out of list that has a max index of 9 will throw that error.

Just need to change to for(int i = knightsList.Count - 1; i > 0; i-- )