2016-09-27 61 views
1

加载我使用DownloadHandlerTexture.GetContent让我的纹理时一个Texture2D可读的统一:制作从服务器

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); 
} 

我想加载之后将其缓存到一个文件中,所以我做的:

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

在这一点上,我得到异常:

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. 

我在想,我需要它在某种程度上可读。我搜索了它,但我得到的唯一答案是如何通过编辑器使其可读。

回答

2

您可以存储来自UnityWebRequest的数据。你为什么对我来说有点无用。将结果转换为纹理以将纹理转换回字节[]。

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

我猜这应该做。在存储原始字节数组时,不需要.png扩展名。然后,您将得到阵列和创建一个纹理出来的:

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

我m加载纹理以在我的模型中使用它。但是当程序结束时,我试图将它缓存到文件中。我使用'DownloadHandlerTexture.GetContent'的原因是因为它针对内存进行了优化。 – serge

+0

而不是缓存在最后,缓存当你得到它。这是完全一样的。 – Everts

+0

听起来很合理,我会在我回家时尝试,并尽快报告。从字节加载纹理而不是使用'DownloadHandlerTexture.GetContent' – serge

2

只是想指出的是,UnityWebRequest.GetTexture可以采取两个参数:URL和一个布尔值,使纹理可读与否:) https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.GetTexture.html

所以在使用DownloadHandlerTexture.GetContent来获取请求结果中的纹理之前。只需调用UnityWebRequest.GetTexture(url,false);所以下载的纹理变得可读。 PS:在Unity 5.6之前要小心,bool nonReadable是反转的。他们应该从5.6开始修复它(根据发布说明)。

为了让你的纹理可读:

  • 之前5.6: UnityWebRequest.GetTexture(URL,真)
  • 5.6之后: UnityWebRequest.GetTexture(URL,FALSE)