0

I want to develop a net game by Unity. I use thread to run loop for sockets' communication. There will be some reactions when the client's socket receive some orders.But UI can only be changed in main thread.

So I have to make some flag variables to be turned on/off in those callback function, and checked in Update function to make some change.

Is there any easy way to solve this problem?

KyleCTX
  • 41
  • 9
  • Before doing any of that you should read this: https://stackoverflow.com/a/54184457/294884 threading + frame based system causes vast confusion – Fattie Jan 14 '19 at 15:51

1 Answers1

1

Unity allows multithreading but in a limited way. If you want to use multiple threads, that's fine. But you should not do any scene or asset related operations in these threads.

I think the most easiest way to get over this is to delegate scene/asset related operations to main thread. In your case, you can add all incoming network data to a Queue in your thread. Then you can consume the data in main thread, which could be one of your scripts' Update method.

Keep in mind that you have to lock Queue when you add/get data. Otherwise more than one thread end up accessing the Queue at the same time. Look at C# locking mechanism and Queue.Synchronized for more info.

OR

If threading feels overwhelming, you can forget threading and use non-blocking methods. It will allow you to do networking in your Update methods. See below

https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.blocking%28v=vs.110%29.aspx

And take a look at 'asynchronous' methods here

https://msdn.microsoft.com/en-us/library/System.Net.Sockets.Socket_methods%28v=vs.100%29.aspx

Can Baycay
  • 875
  • 6
  • 11
  • Thanks for your answer. My current solution is accroding to [Queue](http://blog.kibotu.net/unity-2/unity-start-coroutines-main-thread-anything-else-matter) which is similar to your easiest way.BTW, It seems that mono doesn't support 'async' well. – KyleCTX Apr 13 '15 at 09:47