I’ve seen alot of posts on how the Unity3d engine isn’t thread safe. However very few posts on how you can safely use multi-threading within Unity3d. If the engine wasn’t designed for multi-threading adding the current check is the only right thing to do. However that doesn’t mean threading isn’t supported! Or isn’t safe. It just means that Unity3d won’t try to handle all the weird race conditions that threading involves.
I’m currently making a small MMO (what an oxymoron I know!) never the less I feel I’ve narrowed the project enough that its not a monomental achievement. Blog with project outline
Now let me make it clear. I’m not using multi-threading cause its cool. Or because I have huge calculations. I use it cause most actions needs to swing by a server to be validated and/or randomized! I’m using the ASP.Net client generated by mono’s wsdl and it has two modes, blocking and async. I’m going for async and that means I get my replies in a different thread.
First I looked for methods to invoke back to main thread, but found none. Even more so I found several posts saying I’m a dummy cause I insist on using threads.
Well luckily I previously did an advanced CommandQueue system. It works a bit like co-routines, it takes a bit longer to define you commands, however its slightly better suited for scripted animations and such. But the main advantage ofcourse is that it allows me to add commands in a thread-safe way and then execute them in main thread.
So my two cents to all with a similar problem. Make an abstract object with an abstract run() method. Then derive an object from that which holds the needed context information (perhaps a delegate to invoke) add it to a thread-safe list. You can then run through the list on Update() and voila!
Alternate/Simpler solutions:
-
GabrielH suggests adding coroutines to a list and then starting the coroutine from main-thread.
-
If you just want a quick fix take PragmaScript’s solution cause it has source code. Though I’d recommend swapping the list with an empty one. Then you can release the lock and call the actions without risking thread-locking issues.
Since I’m new with Unity3d I hope someone can point me towards the new feature suggestions page. Cause an InvokedCoroutine that calls the coroutine on main-thread would certainly solve most user problems.