How can I simulate a thread?
I'm execute a large piece of code and it freezes everytime. I'm trying to execute this code in the background so it doesn't freeze all game, but this seems to be imposible since Unity isn't thread friendly (thing that I don't understand). Any suggestions? I can't use threads since I'm using random class.
Answer by Dave-Carlile · Aug 31, 2015 at 04:09 PM
You can use threads in Unity with the limitation that anything using the Unity API/Rendering must be called on the main thread. So depending on what your background task is doing this may be a viable option.
Otherwise you can use Coroutines which is a sort of cooperative multitasking that allows you to easily spread work across frames.
I forgot to put that I'm using Random class in that code (fixed right now). I've tried to use corroutines but it still freezes my game.
In your Coroutine you have to yield at appropriate times in order to split up the work. What does your coroutine look like?
Now I figured how to correctly use those corroutines. Thanks very much. Is it possible to call a corroutine inside another corroutine?
Yes, and you can wait for it to complete before continuing on as well. The StartCoroutine documentation has an example.