- Home /
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?
Answer by Stormizin · Jun 28, 2013 at 06:31 PM
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?
Works better. At least on my machine. But is there no better-perfor$$anonymous$$g way to remove the trees? There has to be one..
All that i know is, that you can put the trees in memory and hold. Since you call the destroy method maybe the performance will improve.
Also you can try Builtin arrays, they are very fast. $$anonymous$$G:
public class example : $$anonymous$$onoBehaviour {
private Vector3[] positions;
void Awake() {
positions = new Vector3[100];
int i = 0;
while (i < 100) {
positions[i] = Vector3.zero;
i++;
}
}
}
Problem is, that I don't know the size the array will have. :/
Your code need to know how many trees will be destroyed. Use a var that will hold this count then execute the builtin array.
Yea, but that's the point. $$anonymous$$y code won't know before he iterates over all the TreeInstances.