Remove Trees during runtime

Hi there,

I have a smiluation and want to build structures in-game. And I want the surrounding trees to be removed when placing a building nearby.
Problem is that my current solution actually does remove the trees within a certain radius. But the game freezes for a few seconds, since there are so many trees.

The code looks similar to this:

TreeInstance[] trees = Terrain.activeTerrain.terrainData.treeInstances;
ArrayList newTrees = new ArrayList();
Vector3 terrainDataSize = Terrain.activeTerrain.terrainData.size;
Vector3 activeTerrainPosition = Terrain.activeTerrain.GetPosition();
float distance;

foreach (TreeInstance tree in trees )
{

    distance = Vector3.Distance(Vector3.Scale(tree.position, terrainDataSize)
                    + activeTerrainPosition, currentObject.transform.position);

    if (distance > 20) {
        newTrees.Add(tree);
    }
}
Terrain.activeTerrain.terrainData.treeInstances = (TreeInstance[])newTrees.ToArray(typeof(TreeInstance));

do you have any suggestions how I might be able to do this faster?

edit: just realised, that when I restart the game after removing trees, they are still gone?! How can I prevent Unity from doing this?

This really depends on the user’s computer.
It’s too many objects getting destroyed at same time.
Getting lots of memory free.

Did you tested with the scene already builded?