1 回答

TA貢獻1808條經驗 獲得超4個贊
一般來說,你應該寧愿使用Path.Combinelike
var path = Path.Combine(Application.persistentDataPath, FileName);
代替系統路徑!可能是您的目標設備根本不理解/為路徑分隔符。
如果文件已經存在(也許是更新的版本?而且你已經下載了它)也可以寫,或者如果它已經存在你甚至不應該開始下載以節省帶寬。
我還認為這WriteAllText不是二進制圖像數據的正確解決方案,因為www.downloadHandler.text已經
解釋為 UTF8 字符串
因此,由于圖像很可能有一些字節在 UTF8 字符串中無法表示,因此您會在此處獲得損壞的數據!
你寧愿直接使用
www.downloadHandler.data
它返回原始byte[]而不是例如File.WriteAllBytes(僅在UWP上)或將其FileStream寫入byte[]文件的正確方法。就像是
var data = www.downloadHandler.data;
File.WriteAllBytes(path, data);
或者
var data = www.downloadHandler.data;
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
fs.Write(data, 0, data.Length);
}
比場景中的白色圖像通常意味著精靈是null.
如果沒有打字錯誤,那么您LoadSprite 總是returns null。你忘了歸還創建的sprite
private Sprite LoadSprite(string path)
{
if (string.IsNullOrEmpty(path)) return null;
if (System.IO.File.Exists(path))
{
byte[] bytes = File.ReadAllBytes(path);
Texture2D texture = new Texture2D(900, 900, TextureFormat.RGB24, false);
texture.filterMode = FilterMode.Trilinear;
texture.LoadImage(bytes);
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, 8, 8), new Vector2(0.5f, 0.0f), 1.0f);
// You should return the sprite here!
return sprite;
}
return null;
}
但是請注意,加載本地圖像的更好方法實際上UnityWebRequestTexture也是如此。它還將本地文件路徑作為 URL 和
與下載原始字節并在腳本中手動創建紋理相比,使用此類可顯著減少內存重新分配。此外,紋理轉換將在工作線程上執行。
但是也
僅支持 JPG 和 PNG 格式。
但這不應該是我想的問題,因為LoadImage到目前為止您使用的也是相同限制的基礎。
但是,這將是異步的,因此您必須等待紋理才能創建精靈。因此,與其重新調整,Sprite我實際上寧愿傳入相應Image組件的引用并直接替換其sprite. 就像是
private IEnumerator LoadLocalTexture(string path, Image receivingImage)
{
UnityWebRequest www = UnityWebRequestTexture.GetTexture(path);
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
var texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
var sprite = Sprite.Create(texture, new Rect(0, 0, 8, 8), new Vector2(0.5f, 0.0f), 1.0f);
receivingImage.sprite = sprite;
}
}
如果您實際上并不一定要使用,Sprites我總是建議您RawImage改用可以直接使用的組件Texture2D!而不是做類似的事情
private IEnumerator LoadLocalTexture(string path, RawImage receivingImage)
{
UnityWebRequest www = UnityWebRequestTexture.GetTexture(path);
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
var texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
receivingImage.texture = texture;
}
}
但是也
注意:請記住,使用 RawImage 會在每個 RawImage 出現時創建一個額外的繪制調用,因此最好僅將其用于背景或臨時可見圖形。
- 1 回答
- 0 關注
- 136 瀏覽
添加回答
舉報