- Home /
Slow for loop
Why does this piece of code run at 300ms? I can't see how it is doing anything expensive:
IEnumerator PaintTheTerrain() {
int aw = Chunk.terrainData.alphamapWidth;
for (int x = 0; x < aw; x++) {
float normalPosX = (x * 1f) / (aw * 1f);
for (int y = 0; y < aw; y++) {
float normalPosY = (y * 1f) / (aw * 1f);
float angle = Chunk.terrainData.GetSteepness (normalPosX, normalPosY);
float height = Chunk.terrainData.GetInterpolatedHeight (normalPosX, normalPosY);
Biome Biome = Biomes.GetPoint (x, y);
if (height < WaterLevel + 2) {
map [y, x, 2] = 1;
} else if (angle > 25) {
map [y, x, 1] = 1;
} else {
map [y, x, Biome.SplatIndex] = 1;
}
}
if (x % 10 == 0) {
progress = (x * 1f) / (aw * 1f);
yield return null;
}
}
Chunk.terrainData.SetAlphamaps(0,0,map);
}
Answer by farhanblu · Mar 18, 2015 at 01:31 PM
Without going deeper into your code, I will guess that the statement "yield return null" is getting called too frequently, which means every iteration is delayed by 'at least' one frame. Normally at 30fps, your loop will run after 0.03 (1/30) seconds every time the boolean expression returns true. Try putting a Debug.Log(x);
for the value of x and see if the boolean expression returns true more than what you desire.
The code without the "yield return null" takes 16 seconds to complete, is there any way to make it quicker?
EDIT: Sorry, forgot the Biome code, which might be what is causing this:
public Biome GetPoint(int x, int y) {
Vector2 nearest = GetNearestPoint(x,y);
int Bne = 0;
for (int i = 0; i < points.Count; i++) {
if (points[i] == nearest) {
Bne = i;
}
}
return LB[Bne].biome;
}
private Vector2 GetNearestPoint(int x, int y) {
Vector2 point = new Vector2 (x, y);
Vector2 nearest = new Vector2 (0,0);
for (int i = 0; i < points.Count; i++) {
if (Vector2.Distance (points[i],point) < Vector2.Distance(nearest,point)) {
nearest = points[i];
}
}
return nearest;
}
I think it is the GetNearestPoint which is causing the problems, since it is basically runing 100 times every point. Which is 104857600 times over the entire scene. I got this fixed by caching the biome points so it would just be one command ins$$anonymous$$d of a 100.
Your answer
![](https://koobas.hobune.stream/wayback/20220613190441im_/https://answers.unity.com/themes/thub/images/avi.jpg)