- Home /
Loading texture resource runtime?
I know we can use script to load an image for example, but they have to be stored in the Resources folder. However, if I build the game into an exe, those file resources are no longer accessible. Then, I could no longer "modify the images" without building the game again via Unity. How can I workaround that?
edit: To clarify, if the game reads from an XML and decides which image to load (say I want to change/add a new portrait for a character, or even allow modders to change it when the game is released), I can neither change the image itself, or add new images (with different file names). These images has to be hardcoded before we build the exe, and no longer being data-driven.
Answer by Tarlius · Sep 04, 2013 at 09:03 AM
You can use AssetBundles, or use Texture2D.LoadImage() to load a png or jpeg.
If you want to do something more clever, you can also create empty textures and pass the NativeTextureID rebuild them in native code.
I am using the Indie/Free version of Unity, forgot to mention that!
I took a look at the LoadImage function, correct me if I am wrong, but apparently it uses TextAsset which uses the Resources folder as well :(
Looks like there is no easy way out for us!
"This function loads a JPG or PNG image from raw byte[] array."
You can use standard c# file loading methods to get the byte array. For example, File.ReadAllBytes
Wow thanks a lot, I didn't know about that function (came from C). This should really be in the documentation as an example!
I'll admit that an example that relies on a text asset isn't the most intuitive example... Like you say, if you have an image as a text asset you could have just imported it as an image, after all.
Watch out for this kind of thing in other places too. There is usually an option for reading directly from a byte array/stream for most things (to cover use cases like yours).
Indeed. Thanks for the heads up!
By any chance, do you know how can we remove the nearest power of 2 property that Unity impose on the texture while my singleton is calling LoadImage?