- Home /
MonoBehaviour.Invoke and Threading
I'm trying to invoke a method from a different thread using MonoBehaviour.Invoke.
But i get weird errors:
UnityEngine.MonoBehaviour:Invoke(String, Single)
NetworkClient:<createJoinRoom>m__1(Connection) (at Assets\Scripts\Multiplayer\NetworkClient.cs:90)
PlayerIOClient.c__DisplayClass6:<.ctor>b__1(Object, Message)
PlayerIOClient.MsgConnection:GotMessage(piov)
pioq:c(piov)
piov:a(Byte[], Int32, Int32, b, pioq)
pioad:a(Byte[], Int32, Int32)
pios:c(IAsyncResult)
System.Net.Sockets.SocketAsyncResult:Complete()
System.Net.Sockets.Worker:Receive()
Isn't the "invoke" method supposed to be called from other threads? If not what can I use to execute a method on the main Unity thread?
edit: ok here is my workaround to this issue: http://pastebin.com/wJ52J3mE
Answer by Mike 3 · May 31, 2011 at 11:07 AM
There isn't any built in synchronization between user threads and the unity thread. The main issue is a more to do with timing of events rather than the usual synchronization of data issue.
The way I've solved it in the past is to make a synchronization class which takes a delegate and some user data, and places both into a list. That list is then iterated over in Update, with all the delegates being called, with the user data being passed as parameter.
The calling from update part is what makes it work at any rate, since unity expects you to only call into the unity api from its own events
ok thank you. I will do that. seems to introduce some overhead due to locking and polling in the update method so.
Indeed, but it's much better than throwing threading errors :)
Answer by Tom 17 · May 31, 2011 at 11:10 AM
Simply don't use Unity API from a seperate thread. You need to use the functionality that Unity has as coroutines and such. All calls to the engine stuff needs to be synchronized on the main thread, no way around it, no seperate system threads to directly call the API. I did too stumble over it just recently.