2016-09-27 17 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)