Multithreaded Script invocation in Unity3d

2019-05-13 15:42发布

问题:

I was trying to implement multithreaded script execution in Unity3d, but it seems that the there is no way provided by Unity libraries and we have to use System.Threading provided by Mono. But they have mentioned that Unity Scripting is not thread safe.

Can i implement Multithreading safely and efficiently in Unity3D using System.threading or other Platform independent API ? Also how can i make sure that the scripts are running in parallel ?

An example or a link would be highly appreciated.

Regards

回答1:

I needed threading for an iOS application, unfortunately I never found a way to do such in Unity. But you can write a plugin that uses threading. In my application I needed threading for timing a music application, so I wrote an audio plugin library that uses core-audio in xcode and you can do all the threading you want there. But managing syncing between Unity and the plugin is quite painful.



回答2:

Generally speaking you may use multithreading freely. But there is one important caveat: all calls to Unity API must be done from the main thread. So, feel free to use threads for AI, path finding, whatever. In the end you will need to communicate the computation results back to the main thread.

Unity offers an alternative to threads which is sometimes useful: coroutines. They allow you to run your function in fragments (yield and resume) and all is done from the main thread, so you can utilize Unity API. Note however that they are not suitable for heavy computations.