- Home /
Can I load textures at runtime with a smaller memory footprint?
I've got some PNG byte data in my Resources folder that I want to load at runtime on Android and iOS devices. The image file itself is 2048x4096, which equates to an uncompressed RGBA 32-bit image at 32MB, according to the Texture Import Settings.
So, I take my 32MB texture, give it a .bytes extension, and throw it into the Resources folder. Then, at runtime on an Android device, I call this code to load the bytes into a texture:
TextAsset imageBytes = Resources.Load( atlasPath, typeof( TextAsset ) ) as TextAsset;
texture = new Texture2D( 0, 0, TextureFormat.ARGB32, false );
texture.LoadImage( imageBytes.bytes );
texture.name = atlasPath;
Resources.UnloadAsset( imageBytes );
This works well, but we come to my question: is this the best way to load a texture dynamically at runtime to achieve the best performance/memory usage?
Specifically, I've noticed that when I profile memory usage at runtime, my originally 32MB texture is now 64MB in memory! For some reason, the texture size has doubled. Is this a side effect of using the "LoadImage" function? Or does it have something to do with the image being "Read/Write Enabled"? Is there anyway to avoid that sort of memory bloat when loading a texture dynamically like this?
Hmmm...I'm inheriting some code that was using the program "TexturePacker" to generate byte data as part of their asset pipeline. However, I'll try loading Texture2D directly and see if the result is any different. Thanks for the tip!
Ah, big win! I changed it to directly load Texture2D and the texture is back to 32$$anonymous$$B in memory. I suspect that using LoadImage may cause the loaded texture to have Read/Write enabled, which I read somewhere will double the in-memory size of the texture. Loading the Texture2D directly doesn't have that problem.
Thanks again!
It was most likely due to the fact you assigned the bytes to "TextAssets" and then created a new texture out of those bytes (making new texture 32$$anonymous$$B as well as the bytes in TextAsset being 32$$anonymous$$B)
That would make sense, but I'm only seeing one resource at 64$$anonymous$$B, not two separate resources as 32$$anonymous$$B each. In any case, it's an improvement for sure.
Answer by xortrox · Apr 23, 2014 at 07:47 PM
How come you don't load the texture as typeof(Texture2D) instead? Texture2D myImage = (Texture2D)Resources.Load("images/somepicture.png");