Make a "Progress Bar" during a recursive method in C#
Hello !
I'm trying to make a GameObject turning in each frame (like a kind of "wait/progress bar") during a very long recursive method. My Issue is that that object does not turn as expected because my Unity Program stay stuck on a single frame (because the recursive method do not free my frame I suppose). How can I manage to do that ?
my code looks like :
method 1{
StartCorountine("cr1");
}
IEnumerator cr1(){
displayContext(); // does not matter
yield return new WaitForFixedUpdate();
displayTurningObject();
veryLongRecursiveMethode();
hideTurningObject();
}
I'm quite new with Unity so don't hesitate to ask for precisions.
Thanks for Help
Answer by JVene · Aug 23, 2018 at 10:27 PM
Without more context I can only guess. However, you've already identified the problem. Any method that is going to take a long while is going to freeze the Unity game engine if it runs on the main Unity thread. There will be no hope of displaying anything, as no frames will be processed.
This is what threads are for. Without having information on what your recursive routine does (in particular, what data is it processing, does it get involved with Unity objects that the engine may be using at the time), I can't say more than the most general statements.
You are going to want to review some documentation on starting threads. You may need a tutorial on how to use them. Search on the subject and experiment, perhaps even in a stand alone C# project to understand how they work. Doing this will allow the Unity engine to continue running, which is required in order for your animated wait graphics to display.
Coroutines are not threads, they are basically a mechanism for Unity to call a list of function objects (in C++ we call them functors, a related concept) from a list formed by registering coroutines, which Unity calls at an appropriate time within the order of execution. Coroutines can't solve this problem.
Thanks for your answer ! Unfortunately I'm working with a version of Unity that can't use (as I was told) Threads. I will check this information but I think I am in a dead end.
What version are you using? I've found articles that discuss threading in Unity at least as far back as 2012. Even if it were true, there are alternatives. For one, there are ways of reconfiguring a recursive algorithm such that it can run in short bursts over successive Updates until the task is completed (it's an ooooold concept going back to my days in Windows 3.1 and DOS :) ).
I'm using Unity 5.6.5. $$anonymous$$aybe my informations were wrong :D I will try to parallelise that recursive function.
You can use threads in Unity. But you can't call Unity-related functions in a thread not handled by Unity itself (the main thread)
Your answer
![](https://koobas.hobune.stream/wayback/20220612173336im_/https://answers.unity.com/themes/thub/images/avi.jpg)