在开发时遇到了一个很奇怪的问题,使用WebClient来异步下载远程资源,并且使用了WebClient的两个异步回调方法DownloadProgressChanged和DownloadFileCompleted。在Unity编辑器中,两个异步回调方法可以正常执行,当打包后发现,两个异步回调方法根本不会执行,比较神奇的是远程文件居然下载了下来。
通过无数次踩坑,发现是.net版本影响的。见下图:
代码如下:
void Start()
{
downloader = new Downloader(assetName, downloadUrl, savePath);
downloadBtn.onClick.AddListener(DownlodClick);
}
private void DownlodClick()
{
downloader.DownloadFileAsync(progress => { }, status =>
{
var result = (Downloader.DownloadResult)status;
Debug.Log("download status:" + result);
});
}
private WebClient client;
private Action<float> progressHandler;
private Action<int> completedHandler;
public Downloader(string fileName, string downloadUrl, string savePath)
{
this.savePath = savePath;
this.fileName = fileName;
this.downloadUrl = downloadUrl;
uri = new Uri(downloadUrl);
}
/// <summary>
/// 异步下载bundle
/// </summary>
/// <param name="progressHandler">传输进度handler,返回百分比进度值0-100</param>
/// <param name="completedHandler">下载完成handler,DownloadResult类型</param>
public void DownloadFileAsync(Action<float> progressHandler, System.Action<int> completedHandler)
{
cancelled = false;
client = new WebClient();
this.progressHandler = progressHandler;
this.completedHandler = completedHandler;
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
Debug.Log("fileName:" + fileName);
client.DownloadFileAsync(uri, Path.Combine(savePath, fileName));
downloading = true;
client.DownloadProgressChanged += DownloadProgressChanged;
client.DownloadFileCompleted += DownloadFileCompleted;
}
若使用.net3.5,是完全没有问题的;若使用.net4.6,则存在回调方法不执行的情况。
最终踩坑发现,当使用.net4.6时,无法在Unity主线程中使用WebClient的异步回调方法,必需通过开启子线程的方法来执行,修改DownloadFileAsync方法如下
public void DownloadFileAsync(Action<float> progressHandler, System.Action<int> completedHandler)
{
cancelled = false;
client = new WebClient();
this.progressHandler = progressHandler;
this.completedHandler = completedHandler;
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
Debug.Log("fileName:" + fileName);
//开启子线程执行下载和回调方法
Thread t = new Thread(()=>{
client.DownloadFileAsync(uri, Path.Combine(savePath, fileName));
downloading = true;
client.DownloadProgressChanged += DownloadProgressChanged;
client.DownloadFileCompleted += DownloadFileCompleted;
});
t.Start();
}
最终将项目打包后,再测试,问题解决!!!