通过使用UnityEngine.WWW
下载文件,我得到以下错误
OverflowException:数字溢出。
我发现这个错误是由结构本身引起的,因为字节数组的字节数组比int.MaxValue可以分配的字节数多(~2 2GB)。
错误是通过使用www.bytes
返回数组来触发的,这意味着框架可能以其他方式将数组存储在中。
我如何以另一种方式访问下载的数据,或者是否有更大文件的替代方案?
public IEnumerator downloadFile()
{
WWW www = new WWW(filesource);
while(!www.isDone)
{
progress = www.progress;
yield return null;
}
if(string.IsNullOrEmpty(www.error))
{
data = www.bytes; // <- Errormessage fired here
}
}
发布于 2018-06-05 08:20:56
统一新答案( 2017.2及更高版本)
在DownloadHandlerFile
中使用UnityWebRequest
。DownloadHandlerFile
类是新的,用于直接下载和保存文件,同时防止过高的内存使用率。
IEnumerator Start()
{
string url = "http://dl3.webmfiles.org/big-buck-bunny_trailer.webm";
string vidSavePath = Path.Combine(Application.persistentDataPath, "Videos");
vidSavePath = Path.Combine(vidSavePath, "MyVideo.webm");
//Create Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(vidSavePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(vidSavePath));
}
var uwr = new UnityWebRequest(url);
uwr.method = UnityWebRequest.kHttpVerbGET;
var dh = new DownloadHandlerFile(vidSavePath);
dh.removeFileOnAbort = true;
uwr.downloadHandler = dh;
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
Debug.Log(uwr.error);
else
Debug.Log("Download saved to: " + vidSavePath.Replace("/", "\\") + "\r\n" + uwr.error);
}
旧答案(Unity 2017.1及更低版本)如果您想在下载文件时访问每个字节,请使用)
像这样的问题就是为什么Unity的UnityWebRequest
不能直接工作,因为在Unity的最新版本中,WWW
API是在UnityWebRequest
API之上实现的,这意味着如果你在WWW
API上遇到错误,你很可能也会在UnityWebRequest
上得到同样的错误。即使它能工作,你在移动设备上也可能会遇到像Android这样的小内存的问题。
要做的是使用UnityWebRequest的DownloadHandlerScript
特性,它允许您以块为单位下载数据。通过分块下载数据,可以避免导致溢出错误。WWW
应用编程接口没有实现这个特性,所以必须使用UnityWebRequest
和DownloadHandlerScript
来分块下载数据。你可以在here上阅读它是如何工作的。
虽然这应该可以解决您当前的问题,但在尝试使用File.WriteAllBytes
保存大量数据时,您可能会遇到另一个内存问题。使用FileStream
保存部分,并仅在下载完成后才将其关闭。
创建用于分块下载数据的自定义UnityWebRequest
,如下所示:
using System;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
public class CustomWebRequest : DownloadHandlerScript
{
// Standard scripted download handler - will allocate memory on each ReceiveData callback
public CustomWebRequest()
: base()
{
}
// Pre-allocated scripted download handler
// Will reuse the supplied byte array to deliver data.
// Eliminates memory allocation.
public CustomWebRequest(byte[] buffer)
: base(buffer)
{
Init();
}
// Required by DownloadHandler base class. Called when you address the 'bytes' property.
protected override byte[] GetData() { return null; }
// Called once per frame when data has been received from the network.
protected override bool ReceiveData(byte[] byteFromServer, int dataLength)
{
if (byteFromServer == null || byteFromServer.Length < 1)
{
Debug.Log("CustomWebRequest :: ReceiveData - received a null/empty buffer");
return false;
}
//Write the current data chunk to file
AppendFile(byteFromServer, dataLength);
return true;
}
//Where to save the video file
string vidSavePath;
//The FileStream to save the file
FileStream fileStream = null;
//Used to determine if there was an error while opening or saving the file
bool success;
void Init()
{
vidSavePath = Path.Combine(Application.persistentDataPath, "Videos");
vidSavePath = Path.Combine(vidSavePath, "MyVideo.webm");
//Create Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(vidSavePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(vidSavePath));
}
try
{
//Open the current file to write to
fileStream = new FileStream(vidSavePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
Debug.Log("File Successfully opened at" + vidSavePath.Replace("/", "\\"));
success = true;
}
catch (Exception e)
{
success = false;
Debug.LogError("Failed to Open File at Dir: " + vidSavePath.Replace("/", "\\") + "\r\n" + e.Message);
}
}
void AppendFile(byte[] buffer, int length)
{
if (success)
{
try
{
//Write the current data to the file
fileStream.Write(buffer, 0, length);
Debug.Log("Written data chunk to: " + vidSavePath.Replace("/", "\\"));
}
catch (Exception e)
{
success = false;
}
}
}
// Called when all data has been received from the server and delivered via ReceiveData
protected override void CompleteContent()
{
if (success)
Debug.Log("Done! Saved File to: " + vidSavePath.Replace("/", "\\"));
else
Debug.LogError("Failed to Save File to: " + vidSavePath.Replace("/", "\\"));
//Close filestream
fileStream.Close();
}
// Called when a Content-Length header is received from the server.
protected override void ReceiveContentLength(int contentLength)
{
//Debug.Log(string.Format("CustomWebRequest :: ReceiveContentLength - length {0}", contentLength));
}
}
使用方法:
UnityWebRequest webRequest;
//Pre-allocate memory so that this is not done each time data is received
byte[] bytes = new byte[2000];
IEnumerator Start()
{
string url = "http://dl3.webmfiles.org/big-buck-bunny_trailer.webm";
webRequest = new UnityWebRequest(url);
webRequest.downloadHandler = new CustomWebRequest(bytes);
webRequest.SendWebRequest();
yield return webRequest;
}
https://stackoverflow.com/questions/50689859
复制相似问题