- Home /
Update console in the same frame
Hi, I have two loops, one inside other. The process I am doing takes around 9 seconds with 8192 x 8192 iterations. I would like to print a percentage in the outer loop but it seems that console just update on the next frame after the loop.
Pseudo-code:
for(int i = 0; i < 8192;i++){
for(int j = 0; j < 8192;j++){
// Do some crazy stuff here
}
Debug.Log(100f * i / 8192f + "%"); /* Doesn't print until next frame*/
}
I understand why it would be a bad practice to print every time the console updates,in most cases unnecessary and process consuming but since I need it how can I force the console to update? Or I will need to write to a file in the HD to ensure the system stop processing.
Answer by gvergidis · Oct 03, 2018 at 08:26 AM
Hello.
No, it will not print in next frame. It will print when operation finishes. A frame is a loop of ALL commands of ALL scripts running every frame. C# is a serial programming language. What you need is a parallel programming here. When using loading screen, you can not rely on serial programming. That is why there are Coroutines. Try changing your code to this :
private IEnumerator CrazyStuffRoutine()
{
for(int i = 0; i < 8192;i++){
for(int j = 0; j < 8192;j++){
// Do some crazy stuff here
Debug.Log(100f * i / 8192f + "%"); /* Doesn't print until next frame*/
yield return null;
}
}
}
Yield return null means wait a frame, and continue on the next one. So expect this code to run at your fps speed. Ofcourse you can yield return null every 10 steps or 100. This piece of code is not serial and will not halt your total process until it finishes. To call coroutine just use :
StartCoroutine(CrazyStuffRoutine());
I hope this helps.
Be adviced that using Log so many times will consume a great amount of memory. I would suggest to only show progress every 10 loops or 100. Also, wrap your log command inside an #if C# preprocessor directives like so : #if DEVELOP$$anonymous$$ENT_BUILD Debug.Log("Something to log :P"); #endif
This will only be included to your build if you select development build. For more informations about directives, take a look here : Preprocessor Directives
Hi, Thanks for the answer! I liked how complete you wrote it.
I have thought about Coroutines but I didn't want to have to wait until the next frame. Using it every 10/100 steps will do it.
Best regards!
Your answer
Follow this Question
Related Questions
Looping animation while key down 1 Answer
Help! Unsaved work stuck in frozen unity, believed to be from infinite loop. What can i do? 2 Answers
problem with loop / unity crash 2 Answers
Change Color of Material in Loop 1 Answer
NEED HELP! Wave spawner just wont work!,NEED HELP! Wave spawner not working :( 2 Answers