构建Windows应用商店中的WebClient类 - 在Unity中构建错误
我正在为Windows应用商店平台(通用10 SDK)构建统一应用(5.4.0f3)。 我会在hololens上运行它。构建Windows应用商店中的WebClient类 - 在Unity中构建错误
我有一个问题编译我的脚本,它似乎是由于我正在使用的WebClient类。我也尝试在另一篇文章中推荐使用HttpClient,但没有运气。我看到一些人在Unity中使用WebClient类成功构建,但我猜他们没有为Windows应用商店构建。
编译错误我得到: 错误CS0246:类型或命名空间名称“WebClient的”找不到(是否缺少using指令或程序集引用?) 名称“WebClient的”在不存在当前上下文
我刚刚开始使用Unity,但我相信我可以在使用WebClient的代码周围添加一些指令,或者声明新的WebClient,以便它仍然可以编译并能够在hololens上运行。
我发现了“平台相关编译”页面(https://docs.unity3d.com/Manual/PlatformDependentCompilation.html),这似乎解释了这一点。 我试过使用其中的一些(例如UNITY_WSA,UNITY_WSA_10_0等),但没有运气。我目前使用雅虎财务API的方式如下:webClient.DownloadFile(url, stockFile);
,下载.csv
文件。 有什么建议吗?
我注意到你使用了WebClient.DownloadFile
。您应该而不是使用DownloadFile
函数,因为这将等待块,直到文件完成下载。这次发生的事情是,由于主线程被阻塞,UI将被冻结。
如果要使用WebClient
API,则应使用DownloadFileAsync
函数。 Here是如何做到这一点的一个例子。
您可以在Hololens以外的平台上使用WebClient
。然后您可以在hololens上使用WWW
或UnityWebRequest
,然后使用File.WriteAllBytes
在文件完成下载后保存该文件。
的伪代码看起来应该是这样:
#if !UNITY_WSA_10_0
WebClient API
#else
WWW API
#endif
完整代码:
string url = "http://www.yourUrl.com";
string savePath = Path.Combine(Application.dataPath, "file.txt");
int downloadID = 0;
#if !UNITY_WSA_10_0
//Will be used on Platforms other than Hololens
void downloadFile()
{
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DoSomethingOnFinish);
webClient.QueryString.Add("fileName", downloadID.ToString());
Uri uri = new Uri(url);
webClient.DownloadFileAsync(uri, savePath);
downloadID++;
}
void DoSomethingOnFinish(object sender, AsyncCompletedEventArgs e)
{
string myFileNameID = ((System.Net.WebClient)(sender)).QueryString["fileName"];
}
#else
//Will be used on Hololens
void downloadFile()
{
StartCoroutine(downloadFileCOR());
}
IEnumerator downloadFileCOR()
{
WWW www = new WWW(url);
yield return www;
Debug.Log("Finished Downloading file");
byte[] yourBytes = www.bytes;
//Now Save it
System.IO.File.WriteAllBytes(savePath, yourBytes);
}
#endif
使用:
downloadFile();
如果仍然出现错误,那么您还使用Hololens不支持的命名空间。你应该好好处理。让我们的namepsace是System.Net;
,您可以修复它象下面这样:
#if !UNITY_WSA_10_0
using System.Net;
#endif
由于程序员在他的回答中提到,Web客户端不会在HoloLens平台上存在,除了滚动您自己,因为他提出另一种选择是使用一个的Unity资源商店中可用的客户端。我知道HoloLens工作,一对夫妇有:
最佳HTTP
https://www.assetstore.unity3d.com/en/#!/content/10765
Uniweb
https://www.assetstore.unity3d.com/en/#!/content/40505
上有资产商店很多人,但是这是两个我在HoloLens上尝试过。
真棒这工作!我怎么知道协程已经返回? – user3501476
使用'Action'来做到这一点。看看[this](http://stackoverflow.com/a/30270515/3785314)。如果您仍然感到困惑,请为此提出新问题。 – Programmer