How to improve the Performance of Removing Trees during runtime?

Hi there,

do you see any way how to improve the performance of this method?
The moment it reaches the data.treeInstances = _treeList.ToArray(); the game freezes for 1-3 seconds. And I don’t want to imagine how long it will freeze on my team member’s PCs…

Some explanaition:

  • there are around 7000 trees, created with help of the terrain tool

  • the trees that shall be removed were calculated in another method and added to the list of the area included the trees.

    public static IEnumerator RemoveTrees()
    {

     TerrainData data = Terrain.activeTerrain.terrainData;
     TreeInstance[] treeInstances = data.treeInstances;
    
     List<TreeInstance> treesForRemoval = new List<TreeInstance>();
    
     foreach (BuildingArea area in _buildingAreas)
     {
         yield return new WaitForEndOfFrame();
         if (area.IsBought == true)
         {
             if (area.HasTrees == true)
             {
                 treesForRemoval.AddRange(area.treeRemovalList.ToArray());
                 area.HasTrees = false;
             }
         }
     }
     // remove trees
     _treeList.RemoveAll(x => treesForRemoval.Contains(x));
     yield return new WaitForEndOfFrame();
    
     // replace trees on terrain
     data.treeInstances = _treeList.ToArray();
    
     yield return null;
    

    }

Isn’t that what billboarding is for?
I can’t recall the name of the article on wiki that describes this, but try this:
Divide your map into 4 sections using cubes with a transparent texture on them. Add a script to it and use the “OnTriggerEnter()” “OnTriggerExit()” functions in the unity API after selecting the cubes as triggers in the inspector panel. Continue to divide each cube inside itself by 4 sections. You can also use a memory profiling tool to determine where the cubes need to go based on memory usage of your map in those locations.

OnTriggerEnter: Unity - Scripting API: Collider.OnTriggerEnter(Collider)
OnTriggerExit:
Unity - Scripting API: Collider.OnTriggerExit(Collider)