Search code examples
c#unity-game-enginetexture2d

Making a Texture2D readable in Unity when loading from server


I'm using DownloadHandlerTexture.GetContent to get my texture:

www = UnityWebRequest.GetTexture("http://www.example.com/loadTex/?tag=" + tag);
www.SetRequestHeader("Accept", "image/*");
async = www.Send();
while (!async.isDone)
    yield return null;

if (www.isError) {
    Debug.Log(www.error);
} else {
    yield return null;
    tex = DownloadHandlerTexture.GetContent(www);
}

After loading I would like to cache it to a file so I do:

byte[] pic = tex.EncodeToPNG();
File.WriteAllBytes(Application.persistentDataPath + "/art/" + tag + ".png", pic);

At this point I get the exception:

UnityException: Texture '' is not readable, the texture memory can not be accessed from 
scripts. You can make the texture readable in the Texture Import Settings.

I'm thinking that I need to make it readable somehow. I googled it, but the only answers I get is to how to make it readable through the editor.


Solution

  • You could store the data from UnityWebRequest. What you are dong i a bit of useless for that purpose. You turn the result into a texture to convert the texture back to byte [].

    byte[] bytes = www.uploadHandler.data;
    File.WriteAllBytes(Application.persistentDataPath + "/art" + tag, data);
    

    I'd guess this should do. No need for the .png extension as you store a raw array of bytes. You will then get the array and create a texture out of it:

    byte [] bytes = File.ReadAllBytes(Application.persistentDataPath + "/art" + tag); 
    Texture2D texture = new Texture2D(4,4,TextureFormat.RGBA32, false);
    texture.LoadImage(bytes);