Why is my Tree Removal so low-performing when placing a GameObject nearby

Hi

In my City Builder I have a lonely Island which is not urbanized at all. Which means there are lots of trees.
When placing a building on the ground I want the trees to be removed. I actually found out a way to do this. The problems:

  1. It will only work with the first building
  2. Unity freezes while doing it (and while not doint it on the follow-up buildings)

Here’s my code:

foreach (TreeInstance tree in Terrain.activeTerrain.terrainData.treeInstances)
        {
            distance = Vector3.Distance(
                            Vector3.Scale(tree.position
                                      , Terrain.activeTerrain.terrainData.size)
                            + Terrain.activeTerrain.transform.position
                            , _temporaryBuilding.transform.position);

            if (distance > 25f)
            {
                //Terrain.Destroy(tree); TODO is there a way to use destroy?
                treeInstances.Add(tree); // treeInstances is an ArrayList declared earlier
            }
            Terrain.activeTerrain.terrainData.treeInstances 
                       = (TreeInstance[])treeInstances
                          .ToArray(typeof(TreeInstance));
        }

I can see, that this solution is quite low-performing. Because I always have to add every single tree again. Or at least I guess this might be the reason.
But actually I’ve seen games working just fine with that solution…

But mine is freezing AND the removal won’t work on a second try. Only for the first building.

The problem was
Terrain.activeTerrain.terrainData.treeInstances
= (TreeInstance)treeInstances
.ToArray(typeof(TreeInstance));
which I accidentically put inside the foreach loop.

HI,first try places a group of trees directly as prefab and try removing it using GameObject.SetActive = false;(dont use Destroy
Destroying an object calls GarbageCollector which takes a bit of high memmory.This may the cause unity to freeze if there a lot to destory and has only little memmory

)
If you want an Script that uses GameObject.SetActive = false; please do feel free to ask

Update
Hi here is the sript for the mouse
This script is for birdeye view(Top view)

//omitted Using Unity Engine..etc

public class BuildingPlacer : MonoBehaviour {
public Transform BuildingA;
public Transform BuildingB;
private Transform tgtbuilding;
int treelayer;
void Update(
treelayer = 1<<9 ;` /// -->9 Number of the Tree layer 

treelayer = ~treelayer;
if(Input.GetKeyDown(KeyCode.A)){
tgtbuilding = BuildingA;
}
if(Input.GetKeyDown(KeyCode.B)){
tgtbuilding = BuildingB;
}
if(tgtbuilding){
if(Input.GetButton("Fire1")){
Ray Pos= Camera.main.ScreenPointToRay(Input.mousePosition);///Note your Camera should be Tagged MainCamera
 
RaycastHit hit = hit;
if(Physics.Raycast(Pos,out hit,10000,treelayer) && hit.normal.y > 0.999){
if(hit.collider.tag == "PlaceableArea"){
hit.collider.SendMessage("RemoveTrees",SendMesageOptions.DontRequireReceiver);
PlaceBuilding(tgtbuilding,5,hit.point);
}
}
}else{
Debug.Log("Select the building by pressing A or B");
}
}
IEnumerator PlaceBuilding(Transform obj,float wait,Vector3 pos2){
yield WaitForSeconds(wait);
Instantiate(obj,pos2,Quaternion.FromToRotation(Vector3.up,hit.normal);///for Uneven terrain use Quaternion.FromToRotation(Vector3.up,hit.normal) else use obj.rotation
}
}
}

now Create a box and scale on y axis until it looks like a plane and then tag it PlaceableArea now place Trees overthem manually (Like you place character i.e drag and drop) and create a new layer(le this be on number 9) name them treelayer(or anything you want) and mark the trees and anyobject other than the box tagged PlaceableArea as treelayer

attach this script to the box

//omitted using unity engine...
public class TreeRemover(){
public GameObject[] Trees;//Assign trees place above the box here
void RemoveTrees(){}
foreach(int k =0;k<Trees.length;k++){
Trees[k].SetActive = false;
}

}
}

Hope it works the way you wanted