RemoveAt() not working within for() loop.

I am spawning trees in random locations around my landscape mesh. My code essentially locates all vertices on the landscape mesh, keeps only the vertices that would be good tree locations (based on criteria I’ve set), and saves these vertices in a list called “treeSpawnLocations”. It then determines how many trees to spawn, based on a predetermined “treeDensity” float, and it uses a for() loop to instantiate each tree at a valid tree location (a random “treeType” from an array of tree prefabs, and at a random y rotation).

Here’s where my problem is. I don’t want multiple trees spawning at the same location. So after each tree spawns, within the for() loop, I use treeSpawnLocations.RemoveAt(t) to remove that spawn point from the list of possible spawn locations. The code works perfectly except that multiple trees still spawn at the same locations. The code seems to completely ignore that line. Any idea why?

TLDR: I’m trying to remove an item from a list in each for() loop so that item doesn’t get pulled again in the next loop, but it doesn’t get removed.

Here’s the section of code relevant to my question:

int treesToSpawn = Mathf.RoundToInt(treeSpawnLocations.Count * treeDensity);
for (int i = 0; i < treesToSpawn; i++)
    int t = Random.Range(0, treeSpawnLocations.Count - 1);
    Instantiate(treeTypes[Random.Range(0, treeTypes.Length - 1)], treeSpawnLocations[t], Quaternion.Euler(Quaternion.identity.x, Random.Range(0, 360), Quaternion.identity.z));

RemoveAt works fine. Your treeSpawnLocations contains duplicate entries.

void RemoveDuplicates ( List<Vector3> list )
	var set = new HashSet<Vector3>( list );
	list.AddRange( set );