Removing element from a list after it's destroyed

I’m trying to build a TD game, and in order to handle multiple enemies at once, I’m using a hashtable and a list. The logic’s been working really fine, but I’m having trouble removing the enemy after it’s killed.

The problem is I’m using messages to manage enemy add/removal from the list, using trigger colliders. When the enemy enters tower range, it adds to both the list and the hash and starts shooting. When it leaves, the tower removes the enemy from both the list and the map and switches target. When the enemy is destroyed, however, it doesn’t trigger my “OnTriggerExit2D” function and, thus, is not removed from the list nor the map.

I would do the following:

  • Put the code to remove an enemy from list and hashtable in an extra method of the tower script, e.g. “RemoveEnemyFromList(GameObject enemy)”.
  • call this method from OnTriggerExit2D
  • in the tower update function, check if all enemies in the list are still alive.
  • if an enemy has died, call RemoveEnemyFromList(enemy) from the Update-Function.

Really depends on how you have everything setup, but assuming you can make your list and map static members of your tower script:

public static List<int> test_list = new List<int>() {1, 2};

You can then update the value from any other script just referencing the tower script, so you could run that on the OnDestroy method:

OnDestroy()
{
    TowerScript.test_list.Add(3);
}

Just modifying the list here as you didn’t provide any specific code, but it should be easy to modify to fit your needs.