- Home /
Multi-threaded / non-blocking way of encoding images to Texture2D
I have a image loader in my Unity project that loads a few dozen large PNG / JPG images into the game and then encodes them to Texture2D by simply requesting the WWW.textureNonReadable. The problem is that my main game thread freezes during that last step (several hundred milliseconds per large image). This is very annoying so I'm either looking for a way to (A) do Texture2D creation in a coroutine somehow or (B) create the Texture2D in a separate thread (which seems to be impossible since the Unity API isn't thread-safe) (would it be possible to do the decoding/encoding without Unity API functions / libraries?) (alternatively, would it be possible to run a separate Unity instance that handles file loading / Texture2D encoding and transferring that data back to the main instance?).
Pointers, and preferably examples, will be very much appreciated. Been stuck on this problem for quite a while.
A quick look directed me to this thread, maybe it helps you to create async tasks:
http://answers.unity3d.com/questions/357033/unity3d-and-c-coroutines-vs-threading.html
The problem is that it's a Unity API method that eats up all my processing time, not calculations of my own. So I can't offload it to a different thread. And it doesn't appear to have handles to work with coroutines either.
Ins$$anonymous$$d of encoding textures in real-time while the game is playing, you can substitute for a thumbnail and encode the larger version at a time when the player wouldn't notice the freeze, such as a loading screen.
Not the solution you asked for, but I don't there's an easy fix (or any) unless you rewrite Unity... $$anonymous$$aybe a clever plugin could accomplish this, but I have no idea.
Sadly I can't really hide the loading, my application has an image browsing feature that has to be able to dynamically load images into the 3D environment.
Answer by LightBuzz · Aug 15, 2018 at 02:36 PM
For JPEG images, you could download our Super Fast JPEG plugin from the Asset Store: http://u3d.as/1fxN
The JPEG plugin is based on libjpeg and libjpeg-turbo.
It's faster than Unity's EncodeToJPG() and can also run in background threads.