Debug.Log(...) appears only once per frame?

Quick question, my life doesn’t depend on it, but it made me curious:

Am I correct in believing that all Debug statements appear all together at some pre-determined point in the Unity game loop? I was running some tests involving some lengthy math and async behavior, when I noticed that something along the lines of

//in the main thread
Debug.Log(Calculation started.");
LotsOfMathTakingSeveralSeconds();
Debug.Log(“Calculation complete.”);

led to the frame freezing (expected, given the math) before it printed the “Calculation started” message, and then printing both messages at the same time after the few seconds of math had passed.

I haven’t found anything about this in the documentation, and also I didn’t see anything about when the log gets printed to the console in Unity’s game loop diagram. Does anyone know when the writing of messages to console happens?

Probably because the Console window hadn’t repainted by that point. Most user interface systems don’t always immediately update, but at predetermined points. You probably locked up the main thread before this point.

1 Like

The first message will not appear until 100% of your code stops running. Every method that will be called in a given frame must either run to completion (return) or yield before any message appears.

Unity will lock up 100% of the time EVERY millisecond your scripting code is running.

Nothing will render, no input will be processed, no Debug.Log() will come out, no GameObjects or transforms will appear to update.

Absolutely NOTHING will happen… until your code either:

  • returns from whatever function it is running

  • yields from whatever coroutine it is running

As long as your code is looping, Unity isn’t going to do even a single frame of change. Nothing.

No exceptions.

“Yield early, yield often, yield like your game depends on it… it does!” - Kurt Dekker

That sounds about right, thanks, and confirms what I believed to have observed.

Yes, I had expected the game to freeze. What I had not known until now was the Debug.Log() call doesn’t immediately write to console, but that the log message instead gets “saved” in some list of log messages that are then all written to the console at once. Which will be helpful to know when figuring out how to split the procedural generation (the long math part) into Tasks.

… “No exceptions.” – Except putting it into a Task.Run( () => …) or similar, and the game jumps back and forth between the normal game loop and the math just fine.

Anyway, thanks for the responses.

1 Like

Unity’s editor is essentially running through the same or very similar systems as your games. So any changes to the interface won’t be reflected until everything has finished updating and it’s time for the frame to be rendered.

1 Like