Nested for-loop freezing Unity

for (int i = 0; i < Chunk.Width; i++)
for (int j = 0; j < Chunk.Height; j++)
for (int k = 0; k < Chunk.Length; k++)
//Debug.Log(new Vector3(i, j, k));
//if (random.Next(2) == 1)
// Debug.Log(“Adding block”);
// chunk.Set(i, j, k, testBlock);

Above code works well. However, the editor freezes on play when I uncomment ANY of the lines within the innermost for-loop.

It’s weird that Unity has no problem running the loop when there is nothing in it, but freezes just by adding a Debug.Log line.

I can’t seem to figure out what is the problem, so I would be grateful if anyone can tell me what’s wrong with the code and how I can fix it.

It’s very likely that it simply takes very very long for the for loop to run.
It take Chunk.Width * Chunk.Height * Chunk.Length iterations to run the loop, now if those numbers are large, it could cause unity to seem frozen while it’s running those iterations. Now, Debug.Log is an IO operation which is relatively expensive, so running it 500 x 500 x 500 times will take a long time. And if you do this every frame, then that makes it even worse…

The reason that this doesn’t happen when you have no commands inside the for is simple. The compiler recognizes that nothing whatsoever happens in the for, so it optimizes it by removing the code completely.

If I’m right, first thing you’d want to do is remove the logs because they are a heavy operation. If it still feels stuck, then your design has a performance flaw. Either make the loops smaller, or do them only once in the Start() method, and simply wait for them to finish.