所以我在为Unity编码时遇到了一个大问题。我对C#非常陌生,所以我使用了我在网上找到的例子来制作这段代码。我唯一的问题是没有弹出错误,但它无法正确下载文件。
我使用这段代码是为了让我的用户更容易导入他们经常使用的单元包。我有一个按预期工作的按钮,它显示下载,然后更改为导入(如果文件存在(。然而,如果我点击它,当它说下载时,它会立即说"下载完成",并且文件在几分钟内不会显示。当它最终完成时,文件大小为0KB。
我真的需要帮助,弄清楚为什么我的文件下载不正确。我被难住了。
此代码是WebClient的脚本
using UnityEngine;
using System.IO;
using System.Net;
using System;
using System.ComponentModel;
using UnityEditor;
namespace SentinelsSDK
{
public class SentinelsSDK_ImportManager
{
private static string localPath = "Assets/VRCSDK/Dependencies/VRChat/Imports/";
private static string localDownloadPath = "Assets/VRCSDK/Dependencies/VRChat/Imports/";
private static string urlStart = "https://www.sentinels.xyz/uploads/2/0/9/0/20909832/";
public static void DownloadAndImportAssetFromServer(string assetName)
{
if (File.Exists(localDownloadPath + assetName))
{
sentLog(assetName + " exists. Importing it..");
importDownloadedAsset(assetName);
}
else
{
sentLog(assetName + " does not exist. Starting download..");
downloadFile(assetName);
}
}
private static void downloadFile(string assetName)
{
WebClient w = new WebClient();
w.Headers.Set(HttpRequestHeader.UserAgent, "Webkit Gecko wHTTPS (Keep Alive 55)");
w.QueryString.Add("assetName", assetName);
w.DownloadFileCompleted += fileDownloadCompleted;
w.DownloadProgressChanged += fileDownloadProgress;
string url = urlStart + assetName;
w.DownloadFileAsync(new Uri(url), localDownloadPath + assetName);
}
private static void fileDownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
string assetName = ((WebClient)(sender)).QueryString["assetName"];
sentLog("Download of file " + assetName + " completed!");
}
private static void fileDownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
sentLog("Progress is at " + e.ProgressPercentage.ToString() + "%");
}
private static void sentLog(string message)
{
Debug.Log("[SentinelsSDK] AssetDownloader: " + message);
}
public static void importAsset(string assetName)
{
AssetDatabase.ImportPackage(localPath + assetName, true);
}
public static void importDownloadedAsset(string assetName)
{
AssetDatabase.ImportPackage(localDownloadPath + assetName, true);
}
}
}
此代码是调用从我的其他脚本下载的按钮
using SentinelsSDK;
...
private static string localDownloadPath = "Assets/VRCSDK/Dependencies/VRChat/Imports/";
...
GUILayout.BeginHorizontal();
if (GUILayout.Button((File.Exists(localDownloadPath + "poiyomitoon.unitypackage") ? "Import" : "Download") + " - Poiyomi Toon"))
{
SentinelsSDK_ImportManager.DownloadAndImportAssetFromServer("poiyomitoon.unitypackage");
}
GUILayout.EndHorizontal();
所以我解决了我的问题,但我不确定为什么会出现问题。显然,将"https://"作为urlstart而不是"http://"会破坏它,尽管无论使用何种协议,您都可以正常下载该文件。如果有人能帮我弄清楚为什么会这样,我将不胜感激!