Writing texture to disk changes settings.

Hey guys,

We’re trying to implement a system where textures (sprites) can be downloaded from our server and not only used but stored in the game (so it doesn’t need to be repeatedly downloaded on each session).

I’m able to export and retrieves these asset bundles just fine, the issue comes with trying to save them to disk.

Following suggestions found online, the texture is converted into a byte array and stored by writing these bytes:

byte[] bytes = tex.EncodeToPNG();
System.IO.File.WriteAllBytes(filePath, bytes);

The problem I’m experiencing is that the resulting import settings for the texture are completely different after writing!

The original texture has a Texture Format RGB 24 bit with mip maps disabled and a pixel per unit count of 1.

The stored texture has the generic Texture Format ‘Compressed’, mip maps enabled and a pixel per unit count of 100.

Essentially writing the asset bundle texture to disk results in a texture with wildly different texture settings.

I’ve seen people circumvent this issue by using the TextureImporter class, but as this is editor only it won’t work when we deploy the game to iOS / Android.

Any suggestions?

edit: does not appear to satisfy OP’s request - may be worth knowing how and why so I’ll leave it up.

Unless I’m badly mistaken the same API used by the texture importer editor scripts is available outside the editor namespace.

The best thing you could do would be to establish a convention (policy of settings) used for all such downloadable assets. (Or several policies, if needed, per “type” of texture; you could chose the desired policy by a filename prefix). Your alternative is probably per-file metadata, which I imagine would get messy very quickly.

With this “policy” idea, you’d just run your from-download Texture2D objects through a static script which sets up the properties as you intend. Don’t forget to tex.Apply() the changes after running the object through this static method.

Not a scenario I’ve ever encountered, but I’m quite sure I’ve changed the most critical texture settings at runtime before, so I’m confident this is workable.

Thanks to brianruggeri for the save:

Why not use LoadFromCacheOrDownload like so, to let Unity cache your Asset Bundles. That way your Assets will always have the settings you expect.

I was essentially building a texture / asset storage system that Unity was already providing! Works a charm, thanks!!