Loading a large external image to texture without freezing the game?

I’m building an application with Unity that loads large PNG images from a nearby folder. To do this I use the WWW class (Unity - Scripting API: WWW). After that I load the image file into a texture, which I assign to a Sprite as such:

Texture2D tex = new Texture2D(4, 4, TextureFormat.ARGB32, true);
wwwObject.LoadImageIntoTexture(tex);

Sprite spr = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0, 0), 100);

Uses Unity - Scripting API: WWW.LoadImageIntoTexture

All this works nice and dandy but it freezes the game’s main thread while it’s presumably loading and then compressing PNG files with resolutions spanning from 1080p to 4K. I’ve tried to look for ways to do this in a background thread or something but the Unity API is thread-unsafe and very pissy about that. Is there a way to load these images without freezing my game?

I believe the WWW class is already creating a Texture2D for you, so you should be able to just use the wwwObject.texture (or wwwObject.textureNonReadable) variable instead of creating a new Texture2D, unless as the documentation states that you need to download a different texture continuously. Check out Unity - Scripting API: WWW.texture

Another thing to keep in mind is that when you call LoadImageIntoTexture, it’s going to resize the texture you pass in every time, since you are defining it as 4x4. It is more optimized to be able to replace a texture of the same size as the data, so that could be part of your slow down.

Alternatively, if the wwwObject.texture variable doesn’t work for you for some reason, you can create your own coroutine, and load the data from the wwwObject manually, say 1 row at a time, each frame, until the Texture2D is fully copied, then have some callback at the end of the coroutine to set the texture. During this time, you could set a progress indication.

EDIT: Also note that you should use the WWW.textureNonReadable variable if you don’t need to read pixel data from the texture.