Scott Chamberlain 的解决方案是在 Unity 中执行此操作的正确且推荐WWW
的方法,因为API 在后台处理线程问题。您只需使用协程下载它,然后使用File.WriteAllXXX
Scott 提到的功能之一手动保存它。
我添加了这个答案,因为这个问题是专门询问的,WebClient
而且有时使用WebClient
很好,比如大数据。
问题是你正在让步WebClient
。您不必WebClient
像以前那样在协程中屈服。只需订阅DownloadFileCompleted
将在另一个线程上调用的事件。为了在该DownloadFileCompleted
回调函数中使用 Unity 函数,您必须使用本文UnityThread
中的脚本并在函数的帮助下执行 Unity函数。UnityThread.executeInUpdate
这是一个完整的示例(UnityThread
需要):
public Text text;
int fileID = 0;
void Awake()
{
UnityThread.initUnityThread();
}
void Start()
{
string url = "http://www.sample-videos.com/text/Sample-text-file-10kb.txt";
string savePath = Path.Combine(Application.dataPath, "file.txt");
downloadFile(url, savePath);
}
void downloadFile(string fileUrl, string savePath)
{
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DoSomethingOnFinish);
webClient.QueryString.Add("fileName", fileID.ToString());
Uri uri = new Uri(fileUrl);
webClient.DownloadFileAsync(uri, savePath);
fileID++;
}
//THIS FUNCTION IS CALLED IN ANOTHER THREAD BY WebClient when download is complete
void DoSomethingOnFinish(object sender, AsyncCompletedEventArgs e)
{
string myFileNameID = ((System.Net.WebClient)(sender)).QueryString["fileName"];
Debug.Log("Done downloading file: " + myFileNameID);
//Ssafety use Unity's API in another Thread with the help of UnityThread
UnityThread.executeInUpdate(() =>
{
text.text = "Done downloading file: " + myFileNameID;
});
}