简体   繁体   中英

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.

Just wanted to point out that UnityWebRequest.GetTexture can take two parameters: the url and a bool to make the texture readable or not :) https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.GetTexture.html

So before using DownloadHandlerTexture.GetContent to get the texture in the request result. Simply call UnityWebRequest.GetTexture(url, false); so the texture downloaded become readable.

PS: Be careful, before Unity 5.6, the bool nonReadable is inverted. They should have fixed it starting 5.6 (according to release notes).

To make your texture readable:

  • Before 5.6: UnityWebRequest.GetTexture(url, true)
  • After 5.6: UnityWebRequest.GetTexture(url, false)

You could store the data from UnityWebRequest. What you are dong ia 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM