Hi, community!
Most of code in Unity works with frames, i.g. you do something in Update once per frame or in FixedUpdate once per physics step, but that can cause lags and freezing if your function gets stuck on some reason or just is too hard to compute fast enough to be unnoticed by human eye.
So I was wondering if it is possible to run some code independently of main thread so it will not affect framerate and will be able to be computed for several frames?
The UnityAPI is not thread-safe and has a thread check to prevent you from trying to access it within a thread other than the main thread. It’s possible for you to start a thread to do something completely separate from the UnityAPI, like communicating with a native code plugin.
Essentially, it’s extremely limited. This answer discusses it more fully. Threading in Unity - Unity Answers
If you can’t work within the threading limitations, another option is time slicing your coroutine… basically you set a maximum number of milliseconds your loop is allowed to take, and if it goes over that… yield till the next frame.
I’ve done this for some complex AI flow field generation that just took too long to do in a single update step. I budgeted it 3ms… and it just spread itself out over 4 or 5 frames.