gpt4 book ai didi

c# - 在 Unity C# WWW 中显示进度条

转载 作者:行者123 更新时间:2023-11-30 14:26:53 25 4
gpt4 key购买 nike

我有这段代码可以从服务器下载视频,但我需要显示进度条,这可能吗?我知道我不能有 WriteAllBytes 的进度条

 private IEnumerator DownloadStreamingVideoAndLoad(string strURL)
{
strURL = strURL.Trim();

Debug.Log("DownloadStreamingVideo : " + strURL);

WWW www = new WWW(strURL);

yield return www;

if (string.IsNullOrEmpty(www.error))
{

if (System.IO.Directory.Exists(Application.persistentDataPath + "/Data") == false)
System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/Data");

string write_path = Application.persistentDataPath + "/Data" + strURL.Substring(strURL.LastIndexOf("/"));

System.IO.File.WriteAllBytes(write_path, www.bytes);

}
else
{
Debug.Log(www.error);

}

www.Dispose();
www = null;
Resources.UnloadUnusedAssets();
}

最佳答案

1) 对于 WWW 进度,您可以使用 WWW.progress 属性,http://docs.unity3d.com/ScriptReference/WWW-progress.html ,代码是这样的:

private IEnumerator ShowProgress(WWW www) {
while (!www.isDone) {
Debug.Log(string.Format("Downloaded {0:P1}", www.progress));
yield return new WaitForSeconds(.1f);
}
Debug.Log("Done");
}

private IEnumerator DownloadStreamingVideoAndLoad(string strURL)
{
strURL = strURL.Trim();

Debug.Log("DownloadStreamingVideo : " + strURL);

WWW www = new WWW(strURL);

StartCoroutine(ShowProgress(www));

yield return www;

// The rest of your code
}

2) 如果你真的想要 WriteAllBytes 的进度,将文件写入 block ,并报告每个 block 的进度,例如:

private void WriteAllBytes(string fileName, byte[] bytes, int chunkSizeDesired = 4096) {
var stream = new FileStream(fileName, FileMode.Create);
var writer = new BinaryWriter(stream);

var bytesLeft = bytes.Length;
var bytesWritten = 0;
while(bytesLeft > 0) {
var chunkSize = Mathf.Min(chunkSizeDesired, bytesLeft);
writer.Write(bytes, bytesWritten, chunkSize);
bytesWritten += chunkSize;
bytesLeft -= chunkSize;

Debug.Log(string.Format("Saved {0:P1}", (float)bytesWritten / bytes.Length));
}
Debug.Log("Done writing " + fileName);
}

话虽如此,我个人什至懒得去做 - 与下载时间相比,写入时间微不足道,你真的不需要为此取得进展。

3) 至于暂停按钮,没有办法用WWW类来实现。一般来说,这不是一件容易的事,也不适用于任何服务器。假设您使用 http,您将需要使用 If-Range header 访问服务器,假设服务器支持此功能,以从您上次停止下载的位置获取文件部分。你可以从这里开始http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.27 ,这里https://msdn.microsoft.com/en-us/library/system.net.webrequest%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 ,这里还有一些可能对您有所帮助的示例:

Adding pause and continue ability in my downloader

请注意,在某些平台上可能无法在 Unity 中使用 System.Net 库。

关于c# - 在 Unity C# WWW 中显示进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34376835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com