WebClient Class 正在为 Windows Store 构建 - Unity 中的构建错误

WebClient Class in build for Windows Store - Build Errors in Unity

我正在为 Windows Store 平台(Universal 10 SDK)构建统一 (5.4.0f3) 应用程序。 我会运行在全息镜头上使用它。

我在编译我的脚本时遇到问题,这似乎是由于我正在使用的 WebClient class。我也尝试按照另一个 post 中的建议使用 HttpClient,但没有成功。我看到一些人在 Unity 中使用 WebClient class 成功构建,但我猜他们没有为 Windows Store 构建。

我遇到的编译错误: 错误 CS0246:找不到类型或命名空间名称 'WebClient'(是否缺少 using 指令或程序集引用?) 名称 'webClient' 在当前上下文中不存在

我刚开始使用 Unity,但我相信我可以在使用 WebClient 的代码周围添加一些指令或声明一个新的 WebClient,以便它仍然可以编译并能够 运行全息透​​镜。

我找到了 "Platform dependent Compilation" 页面 (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 function should be used. 是一个示例。

您可以在 Hololens 以外的平台上使用 WebClient。然后,您可以在 hololens 上使用 WWW or 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

正如程序员在他的回答中提到的,Webclient 在 HoloLens 平台上不存在,除了按照他建议的那样滚动你自己的另一种选择是使用 Unity Asset Store 中可用的客户端之一。我知道在 HoloLens 上工作的一对是:

最佳 HTTP

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

联网

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

资源商店中还有很多其他资源,但这是我在 HoloLens 上试过的两个。