How to have a Game Object remove itself from a list? (Unity3d)

Asix Jin picture Asix Jin · Jul 26, 2014 · Viewed 13.4k times · Source

OK so basically I have a list that keeps track of all the enemies in the scene. I am using the list primarily so I can have each enemy check other enemies positions so they don't end up on the same spot. When ever an enemy is created it will add itself to a list, but I need the enemy to remove itself once it's killed. I tried what I have in the code below but it throws me an error (ArgumentOutOfRangeException: Argument is out of range).

void Start () 
{
    Manager.EnemyList.Add(this.gameObject);
    ListSpot = Manager.EnemyList.Count; 
}

//Kills the enemy
public void Kill()
{
    Manager.EnemyList.RemoveAt(ListSpot);
    Destroy(this.gameObject);
}

Answer

Vengarioth picture Vengarioth · Jul 26, 2014

Use a list from the System.Collections.Generic namespace, then you can just call Add and Remove with the instance of the object. It will use the hash functions of the instance to do its thing.

List<GameObject> enemies = new List<GameObject>();
enemies.Add(enemy1);
enemies.Remove(enemy1);

Edit: your solution throws the exception because the index starts by 0 and count will always begin to count at 1. if you add the first element its position is 0, but the count is 1.