- Home /
Problem is not reproducible or outdated
Any Reason this would make Unity Freeze up?
private void PlantTrees(){
int treeTypes = terrain.terrainData.treePrototypes.Length - 1;
int maxZ = (int) terrain.terrainData.size.z,
maxX = (int) terrain.terrainData.size.x;
for(int z = 1; z < maxZ; z++){
for(int x = 1; x < maxX; x++){
TreeInstance tree = new TreeInstance();
float height = terrain.SampleHeight(new Vector3(x,0,z));
if(height > res*0.2){
if(Random.value > .6){
float r = Random.Range(80f, 120f),
g = Random.Range(100f, 150f),
b = Random.Range(20f, 80f);
tree.color = new Color(r,g,b);
tree.heightScale = Random.Range(0.5f, 2f);
tree.widthScale = Random.Range(0.75f, 1.25f);
tree.position.Set(x, height, z);
tree.prototypeIndex = Random.Range(0, treeTypes);
terrain.AddTreeInstance(tree);
}
}
}
}
}
I know this is incredibly vague, but I know it's this bit of code because it runs fine when I comment out the function call. I am at a complete loss at this point, if anyone has a tiny bit of knowledge on this I would greatly appreciate it.
On a side note for some reason this places all the trees in the same place despite having the positions changed... Any ideas why? I have a feeling it's the way I'm instantiating the trees, but I don't know why that wouldn't work.
For default terrain the loop executes 4 milion times, creating around 2.4 milion trees (a bit too much for most computers to handle). What is your terrain size?
Also I think I'm misusing SampleHeight here, but without proper documentation it was sort of a stab in the dark.
I agree with Rett_ it's just too much trees to handle, have you tried this code with a limited small number of trees?
Besides that all i can think of for now is to make sure not to call this in a monobehavior.
I'm calling it inside the OnGui Function, which might be dangerous... I haven't read the full doc on it since I've been focused on actually getting in content before efficiency at this moment. Basically, I have 2 classes for Terrain Generation, and this function is in the higher level script that adds trees and GameObjects and the other one generates a TerrainData object. Thanks for the ideas though, I'm working on this on my own so my thoughts stagnate at times.
Follow this Question
Related Questions
Invisible trees? 1 Answer
Can Tree with terrain system be set up random rotation? 1 Answer
Tree creator and terrain editor 0 Answers
colliders moving in wind 1 Answer
S.O.S: Tiny Tree Issues. 3 Answers