- Home /
Send notification into unity from native thread
I have been implemented a native plugin (dll) where a separate native thread makes some time consuming calculations. When the calculation is done, I want to notify the unity to show a message box about the finished job. But, when i do a call from the native thread into the unity, the unity crashed, even when i set a simple boolean value in c# code. Is there a way how to callback into unity from native thread ?
Thank you
Answer by Bunny83 · Jul 29, 2019 at 10:46 AM
This has little to do with Unity. Unity and the majority of it's API is not thread safe and in addition has a thread check at the beginning which would throw an exception when you try to use it from any other thread then the main thread. So you have to actually execute your code on the main thread. There are several ways how you can do this.
In many cases you would have a specialized thread for a certain task. Though the implementation highly depends on your exact needs (frequency of those tasks and how many there are simultaniously).
Another option is to use something like the generic Loom class that whydoidoit has written a long time ago. It allows you to queue any System.Action for execution on the main thread. The delegate is simply stored in a List and the Update method of the Loom class will actually dequeue and run the code. Of course with proper locking / synchronisation.