Multithreading with gaming machines (Unity3D)?

I use Unity3D and Mono to create a multiplayer online game. C # language script. I know that Unity is not thread safe. C # in Mono allows you to create a new thread using System.Threading . But Unity will prevent the new thread from modifying any of the GameObjects .

In my code, I started a new thread to wait for a callback from my own C code (included in Unity as Plugins ). Thus, when calling the callback, it will be in the new thread, and not in the main Unity thread, which has the authority to manipulate GameObjects. However, I want to modify the GameObjects files. What should I do? Should I use the main thread to poll the new thread? Or is there a better solution?

+4
source share
1 answer

There is more than one way to signal the main stream that data is available in the second stream. Generally speaking, the first method may be the first thread "block" (waiting) until there is a "signal" of the second thread; however, without going into details here, this is not the approach you want to take, since blocking the main thread while doing long calculations on your second thread will make your game unresponsive in the worst case or at best.

So that leaves a different approach that you have taken: polling. However, often you feel the need (once per frame, once every 60 frames), your main thread code (for example, in MonoBehaviour) will want to check the status of the task in the second thread. This can be called by a method or by checking a boolean for an object that "belongs" to a second thread. Using this approach, your task will point to the main stream of the survey, whether things will be β€œdone” or β€œnot done”. Unity co-routines can be a useful mechanism to implement your polling logic from the main thread.

However, you have not done everything yet. If your second stream will repeatedly generate new data in the same variable or buffer, you must also make sure that your main stream will not be read from the buffer that is written by your second stream at the same time. For small amounts of data, you can use the double buffering method (two buffers / variables, one for reading, one for writing, which is replaced with a pointer / link exchange) when the new data is ready; or you can use C # locks (but this can block your main thread with the side effects described earlier).

As soon as your main stream has the data it needs, you can, of course, proceed to change game objects from the main stream.

Please note that your question is not so specific to Unity. Most user interface interfaces have this limitation (with good reason), and communication between threads is solved in the same way in each case.

+10
source

All Articles