簡體   English   中英

用於Windows應用商店的構建中的WebClient類 - 在Unity中構建錯誤

[英]WebClient Class in build for Windows Store - Build Errors in Unity

我正在為Windows Store平台(Universal 10 SDK)構建一個統一的應用程序(5.4.0f3)。 我將在hololens上運行它。

我在編譯腳本時遇到問題,這似乎是由於我正在使用的WebClient類。 我也試過在另一篇文章中推薦使用HttpClient,但沒有運氣。 我見過一些人在Unity中使用WebClient類成功構建,但我猜他們沒有為Windows Store構建。

我得到的編譯錯誤:錯誤CS0246:找不到類型或命名空間名稱'WebClient'(您是否缺少using指令或程序集引用?)當前上下文中不存在名稱'webClient'

我剛剛開始使用Unity,但我相信我可以在使用WebClient的代碼周圍添加一些指令,或者聲明一個新的WebClient,這樣它仍然可以編譯並能夠在hololens上運行。

我找到了“平台相關編譯”頁面( https://docs.unity3d.com/Manual/PlatformDependentCompilation.html ),它似乎解釋了這一點。 我嘗試使用其中的一些(例如UNITY_WSA,UNITY_WSA_10_0等),但沒有運氣。 我目前正以下列方式使用yahoo finance API: webClient.DownloadFile(url, stockFile); 下載.csv文件。 有什么建議么?

我注意到你使用了WebClient.DownloadFile 應該使用DownloadFile函數,因為直到文件完成下載此將等待塊。 這次發生的事情是,由於主線程被阻止,UI將被凍結。

如果要使用WebClient API,則應使用DownloadFileAsync函數。 是一個如何做到一點的例子。

您可以在Hololens以外的平台上使用WebClient 然后,您可以在UnityWebRequest上使用WWWUnityWebRequest ,然后使用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不支持的命名空間。 你也應該處理好這個問題。 我們的名字是System.Net; ,你可以像下面這樣解決它:

#if !UNITY_WSA_10_0
using System.Net;
#endif

正如程序員在他的回答中提到的那樣,在HoloLens平台上不存在webclient,除了滾動自己,因為他建議另一種選擇是使用Unity資源商店中可用的客戶端之一。 我認識的一對HoloLens工作的是:

最好的HTTP

https://www.assetstore.unity3d.com/en/#!/content/10765

Uniweb

https://www.assetstore.unity3d.com/en/#!/content/40505

資產商店還有很多其他產品,但這些是我在HoloLens上嘗試過的兩款產品。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM