Remove from list ?????? (help)

Hi…

I Have a problem…when my character attacks the enemy, then adds to the list of enemies … but the problem NO removed from the list when he died (and when destroy it give me error )

int	ls=EnemyList.Count;
				for (int i = 0; i < ls; i++){
		                Health hp=(Health)EnemyList[i].transform.GetComponent("Health");
						 hp.currentHealth=hp.currentHealth-Damage;
		
							if(hp.dead){   HERE TO REMOVE LIST ????? }

¿how can remove all enemy list ,when the enemy die ???

(sorry my english)

Hi technotdc,

You need to condition check in your list to see if the character that died is the same one as the character in your list or array.

Then when you want to remove the enemy from the list in pseudo-code, you do something like,

if(thisEnemy.tag == EnemyList[i].tag) {
     EnemyList.RemoveAt(i);
}

You can condition check in other ways to see if the enemy you want to remove is the same one that died. Here is a link to the msdn list documents, you can try using some of those remove methods/functions. Link: List<T> Class (System.Collections.Generic) | Microsoft Learn

Sorry if I didn’t explain it too well.

Good luck!

Thanks velo222…

(fixed)

It’s worth mentioning that removing items from a collection as you’re enumerating that collection isn’t a particularly good idea. You could either copy the source list and enumerate the copy or maintain a separate list of items to be removed and enumerate the “removal” list afterwards using Remove() instead of RemoveAt()

Excellent advice. One other option would be to iterate through the list backwards and remove interesting items along the way. So, something like this:

for (int i = MyList.Count - 1; i >= 0; i--)
{
   if (thisItemShouldBeDeleted)
   {
      MyList.RemoveAt(i);
   }
}

That way, the current index is not compromised by the removed item…

Jeff