Files
JJBB/Assets/Project/Script/AssetManagement/BundleDownload/BundleDownloader.cs
2024-08-23 15:49:34 +08:00

93 lines
3.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine.Events;
namespace AssetManagement
{
// 2020.01.04 - Blastom因为当前版本UnityWebRequest不支持下载https
// 现在下载部分无法重用AsyncLoadHub
// 快速解决方案是复制AsyncLoadHub 修改为支持BestHttp的流程
// BestHttp当前没有找到 支持直接下载到文件流的方法,暂时只能下载到内存,然后转存到硬盘
public class BundleDownloader
{
private AssetUpdateDownloader _downloader;
private AssetPathHub pathHub;
public string name { get; private set; }
public int priority { get; set; }
public string error { get; private set; }
public AsyncLoadUnitState state { get; private set; }
public AssetUpdateDownloaderTick.DownloadTimer downloadTimer { get; private set; }
// 失败重试次数
public int failCount { get; private set; }
public event UnityAction<BundleDownloader> onComplete;
// 等待时间结束
public event UnityAction<BundleDownloader> onWaitUp;
public void SetRetry(float time)
{
failCount++;
state = AsyncLoadUnitState.Idle;
downloadTimer = AssetUpdateDownloaderTick.instance.AddTimer(time, OnWaitFinish);
}
public void Init(AssetPathHub pathHub, string assetName, int priority)
{
name = assetName;
this.priority = priority;
this.pathHub = pathHub;
}
public void Load()
{
if (state != AsyncLoadUnitState.Loading)
{
error = string.Empty;
var uriPath = pathHub.GetDownloadPath(name) + AssetConst.bundleVariant;
_downloader =
new AssetUpdateDownloader(uriPath, pathHub.GetPersistPath(name + AssetConst.bundleVariant))
{onComplete = OnComplete};
_downloader.Start(30f);
}
}
// 取消下载仅仅在关闭App时调用
public void Dispose()
{
if (_downloader != null)
{
_downloader.onComplete = null;
_downloader.Dispose();
}
_downloader = null;
}
public float GetProgress()
{
return _downloader == null ? 0f : _downloader.progress;
}
private void OnWaitFinish()
{
AssetUpdateDownloaderTick.instance.RemoveTimer(OnWaitFinish);
downloadTimer = null;
if (onWaitUp != null)
onWaitUp(this);
}
private void OnComplete(AssetUpdateDownloader downloader)
{
if (downloader.error == AssetUpdateManager.AssetUpdateError.FileCreateError)
error = string.Format("File Create Error: failed to create file for {0}!", name);
else if (downloader.error != AssetUpdateManager.AssetUpdateError.Success)
error = string.Format("Download Error: failed to download file for {0}!", name);
else
error = string.Empty;
state = AsyncLoadUnitState.Done;
if (onComplete != null)
onComplete(this);
}
}
}