文章目录
提醒
部分API需要将Unity的 Edit/PrejectSetting/Player/OtherSetttings/AConfiguration/ApiCompatibilityLevel 设为.NetFramework 才可以使用
下载一个资源并保存到本地
csharp
private IEnumerator DownloadFormServer_IE(string url, string path)//从服务器下载资源 path保存路径
{
Debug.Log("正在下载" + url);
string assetName = Path.GetFileName(url);
UnityWebRequest request = UnityWebRequest.Get(url);
request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ProtocolError || request.result == UnityWebRequest.Result.ConnectionError)
{
Debug.Log(request.responseCode);
Debug.Log(request.error);
yield break;
}
while (!request.isDone)
{
string totalDownloadDataStr = "0kb";//总下载量 不是下载速度,可以根据总下载量计算下载速度
if (request.downloadHandler != null && request.downloadHandler.data != null)
{
float speed = request.downloadHandler.data.Length / 1024;
if (speed > 1024)
{
speed = (speed / 1024);
totalDownloadDataStr = speed.ToString("f") + "mb";
}
else
{
totalDownloadDataStr = speed + "kb";
}
}
//打开一个面板显示下载进度条 UIKit是QF框架提供的API
UIKit.OpenPanel<AlertPanel>(new AlertPanelData(
"正在下载" + assetName + "\n"
+ "进度" + (request.downloadProgress*100).ToString("f") + "% "+ totalDownloadDataStr + "\n"
+ "第" + (assetsManagerModel.currentDownlaodFinishIndex + 1) + "\\总共" + assetsManagerModel.waitDownloadAssetsList.Count
));
yield return null;
}
DownloadHandler downloadHandler = request.downloadHandler;
Debug.Log("下载完成");
byte[] data = request.downloadHandler.data;
using (FileStream fs = new FileStream(path, FileMode.Create))//将下载好的数据写入本地
{
fs.Write(data, 0, data.Length);
}
}
下载一张图片
csharp
private IEnumerator DownloadOnePicture_IE(string url, Action<Texture2D> callBack)//在callBack里可以直接对下载的图片进行例如给精灵赋值这类操作
{
if (string.IsNullOrEmpty(url)) yield break;
UnityWebRequest request = UnityWebRequestTexture.GetTexture(url);
yield return request.SendWebRequest();
Texture2D texture2D = DownloadHandlerTexture.GetContent(request);
callBack?.Invoke(texture2D);
}