I am a hobbyist working with Unity, not a professional, so I’m still trying to learn about how to multi-thread some things (and what things can be multi-threaded). With this in mind, I have a calculation that I would like to off-load to a different thread. I’m calculating the “velocity” of a unit in my game every 0.2 seconds in order to trigger what animation state the unit should be in at any given moment. This calculation will need to be done for possibly hundreds of units in the game…so having another thread do it would be great for performance (I think).
The core of the equation is fairly simple and is essentially this code:
I could use sqrMagnitude as well of course if necessary. But could this equation be done in a different thread?
If so, how do you give the result of the calculation back to the main thread, or have the main thread grab the result from the other thread?
My main question though, is simply if it’s even possible to multi-thread something like this? I can research how to code it later on if it actually is possible. Thank you.
No, unfortunately the API cannot be threaded. Unity’s primary solution is the Coroutine, or alternatively InvokeRepeating for calling periodic functions… they both still run on the main thread, however.
If you’re in another thread, what does ‘Time.deltaTime’ mean? It’s defined as being the amount of time since the last frame, but if you’re in another thread with no frames, what could it even mean?
Also, this isn’t that intense of work, this could easily be done on the main thread with very little concern. A place where deltaTime has significance.
Ok, thanks grizzly. Ya Coroutines will not help me that much, since they are on the main thread as well.
I see what you’re saying lordofduct. I know it’s not that intense all by itself, but when hundreds of units are all doing it around the same time, it will add up. Since it won’t work anyways, I guess it’s a moot point now. Thank you though.
I’ll have to seek another solution then. Thanks guys.
Threading something as simple as this is almost always going to be completely unnecessary. There would have to be thousands of units before you even notice a slight impact on performance. You should spend more time profiling and finding the real bottlenecks of your code.