I want to display an image in unity (with C# scripts) and I need to create a thread to implement it. However, the program said that LoadImage() can only be called from the main thread. In this case, how can I display the image? (I must use multithreads)
Asked
Active
Viewed 817 times
0
-
1You can't. Most of the Unity API can only be used in the mainthread. Unfortunately basically all common Texture2D stuff can only be used synchronous. Except maybe you could try [ECS](https://docs.unity3d.com/2018.3/Documentation/Manual/JobSystem.html) but it's a bit tricky to set it up – derHugo Jan 28 '20 at 07:16
-
1Why must you use "multithreads"? – Enigmativity Jan 28 '20 at 07:16
-
You could start a new thread from main thread, passing a reference to a byte array. In the secondary thread, you do the deserialization of the data. When done, kill the thread, your main has the reference to the data you can pass to LoadImage. – Everts Jan 28 '20 at 07:19
-
@Everts that's true .. but still `LoadImage` itself is running in the main thread ;) And it is quite expensive as well – derHugo Jan 28 '20 at 07:20
-
U can run specific operation in main thread . Have a look https://stackoverflow.com/questions/54206912/c-unity-failing-to-call-unity-method-from-asynchronous-method/54213244#54213244 – auslander Jan 28 '20 at 08:07
-
@Enigmativity Well.. That is because I need to create a thread to continuously receive data of image (using socket) and display it in unity ... :( – Yuki Jan 28 '20 at 08:30
-
@derHugo Thank you so much. Btw, is there any way that I can use socket to receive data without creating a thread? My friend told me that if I dont create a new thread, the main thread will be blocked:/ – Yuki Jan 28 '20 at 08:32
-
sure as Everts already mentioned: You should do everything in a thread that is not Unity API related. For receiving socket data there are plenty of examples online. The only thing you need to do is then "dispatch" the received data back to the main thread at some point. Also for this there are solutions online (just search for Unity Mainthread dispatcher) – derHugo Jan 28 '20 at 09:03
1 Answers
-1
Like already said, LoadImage
runs in the main thread and its not impossible to get it on another thread.
One way around your problem would be to use native plugins, which unity supports.
There is for example some information in the documentation Low-level native plug-in interface and an example package given by unity.
Here also a good question/answer related to your question.

Perazim
- 1,501
- 3
- 19
- 42