- Home /
Unity freezes when calling terrainData.SetHeights
I am trying to use Mathf.perlinnoise to randomly create terrain for my game, but whenever I call terrainData.SetHeights unity just freezes and stops responding. I looked around but didn't find anyone else encountering this problem. Is there something obvious I am overlooking in my code? I am using unity 4.0.0f7
void generateMap(int seed, int perlinwidthperpixel) {
Random.seed = seed;
float[,] heights = new float[(int)terrain.terrainData.heightmapWidth, (int)terrain.terrainData.heightmapHeight];
Debug.Log(terrain.terrainData.heightmapWidth);
Debug.Log(terrain.terrainData.heightmapHeight);
for (int i = 0 ; i < terrain.terrainData.heightmapWidth ; i++) {
for (int k = 0 ; k < terrain.terrainData.heightmapHeight ; k++) {
float perlin = Mathf.PerlinNoise(i*perlinwidthperpixel,k*perlinwidthperpixel);
heights[i,k] = perlin;
}
}
terrain.terrainData.SetHeights(0,0,heights);
}
You could speed that up a little by assigning terrain.terrainData.heightmapWidth/heightmapHeight to variables, and using the variables in the loops, so heightmapWidth and Height aren't constantly evaluated every loop iteration.
Answer by Doeko · Aug 18, 2013 at 03:02 PM
SetHeights for larger terrains is very slow and generating the Perlin noise will also take a bit of processing. Most likely it is not crashed but simply executing the function. Wait a while longer and see if it finishes or experiment with a terrain with a very small resolution, such as 128x128.
You could stick it into a coroutine if you don't want the game to freeze while executing the method.
SetHeights only takes a few seconds for max-size terrains (4097x4097), and a fraction of a second for 1025x1025. It's also an atomic operation, so putting it into a coroutine will do nothing; coroutines aren't threads.
The perlin noise doesn't take up much time, when commenting out the setheights function it only freezes for about a second or less. I have had it running for over half an hour in the background, so if it would ever load, it would have already done so. I also noticed that when I change heights[i,k] = perlin;
to heights[i,k] = 1.2f;
or any other random float, it does load.
Answer by Citiral · Aug 18, 2013 at 04:44 PM
I managed to fix the problem partially. If I use terrain.terrainData.heightmapHeight-1
instead of terrain.terrainData.heightmapHeight
in my code everything works just fine. This does cause the last vertices of my terrain to not by affected by the generation, which is a problem. Is this a bug in unity?
Never$$anonymous$$d, I had a really, really stupid bug in another bit of code that caused this problem. I'm sorry for the trouble :)