# How can I destroy trees when placing a building in an RTS?

I am developing RTS game. When I build buildings on the Terrain, any trees that were in that location end up intersecting with the building.

I want to remove all trees from the building's footprint when placing.

Can I use the building's OnTriggerStay to detect tree colliders with a particular tag and destroy the trees? Or is there a better way to clear out these trees?

• I don't think OnTriggerStay is the right tool for this job, since I wouldn't expect either your trees or the buildings to have Rigidbodies. At least one of the colliders needs a dynamic body to fire trigger messages. It sounds like you want something more like Physics.OverlapBoxNonAlloc to get an array of all the trees overlapping your building's location. Jul 30 '19 at 18:25
• I am in a poor level in the programming I can for now get trees in Terrain what about Physics.OverlapBoxNonAlloc It was something advanced Jul 30 '19 at 18:53
• I don't understand your question. I recommend reaching out to a friend who has more practice with English to ask if they can help interpret or proofread for you, to he sure you're understood accurately. Jul 30 '19 at 19:04
• Excuse me for a very me bad language to notice this after Edited question Jul 30 '19 at 19:06
• I'll try Physics.OverlapBoxNonAlloc thank you Jul 30 '19 at 19:09

Here is my solution:

void Update()
{

TerrainData terrain = Terrain.activeTerrain.terrainData;
ArrayList instances = new ArrayList();

foreach (TreeInstance tree in terrain.treeInstances)
{
distanceG = Vector3.Distance(gameObject.transform.position, tree.position);

distance = Vector3.Distance(Vector3.Scale(tree.position, terrain.size) + Terrain.activeTerrain.transform.position, transform.position);

if (distance < closeRange)
{
// the tree is in range - destroy it
print("1");
}
else
{
// tree is out of range - keep it

}
}
terrain.treeInstances = (TreeInstance[])instances.ToArray(typeof(TreeInstance));

}

• You might want to mark this answer as the accepted one :) Aug 25 '20 at 0:58

When you place the building you could search for any tree object in a certain radius around it and if it's less than a certain distance delete them. That way you wouldn't need collision.

You would need a reference to the trees in the scene to access their position information.

• That looks to be what NADER LABBAD is already doing in the answer from a year ago, no? Aug 24 '20 at 23:28
• My bad, didn't even notice the date. I'm still getting used to this sites UI Aug 24 '20 at 23:57

Assuming your buildings have a rectangular base, you can use Physics.OverlapBox / Physics2D.OverlapBox to get all the colliders which overlap the area where you want to put down the building and decide what to do with them depending on object type.