Remove Spawn point from List

I have a list of spawn points, I am trying to have the enemy object pick a random spawn point, and then once that spawn point is used remove that from the list of possible spawn points. Only when the enemy is destroyed is that spawn point added back in to the list.

Here is my code:

  void CreateCapitals(int count)
  {
    enemies = new List<GameObject>();
    GameObject newEnemy;
    List<Transform> freeSpawnPoints = new List<Transform>(capitalSpawnPoints);
    for ( int i = 0; i < count; i++)
    {
      if (freeSpawnPoints.Count <= 0)
      {
        return; // Not enough spawn points
      }
      else {
        int index = Random.Range(0, freeSpawnPoints.Count);
        //int spawnPointIndex = Random.Range (0, capitalSpawnPoints.Length);
        // create a new instance of the enemy prefab, set it to 0,0,0 with rotation 0,0,0
        Transform pos = freeSpawnPoints[index];
        newEnemy = TrashMan.spawn (capitalPrefab, pos.position, pos.rotation) as GameObject;
        newEnemy.name = "Capital_" + i;
        enemies.Add(newEnemy);
        currentCapitals = currentCapitals + 1;
        freeSpawnPoints.RemoveAt(index);
        Debug.Log (freeSpawnPoints[index]);
      }
    }
  }

However index is never removed from the list, and even when I try index–, the enemies continue to spawn despite having the return. Note ‘TrashMan.spawn’ is the object pooling.

Maybe problem with:

int index = Random.Range(0, freeSpawnPoints.Count - 1);

Index can’t be = list.count because it start from 0 (zero) so max index is list.count - 1; But not sure that problem only in this.

Where and how often do you call that method (CreateCapitals)? How many spawn points do you have in the “capitalSpawnPoints” array?

Instead logging freeSpawnPoints[index] in line 22 you might want to check the Count of the list:

Debug.Log ("Free spawnpoints: " + freeSpawnPoints.Count);

If CreateCapitals is only called once i don’t see any problem at the moment.