[游戏开发][Unity]Assetbundle下载篇(5)开始下载AB包

目录

打包与资源加载框架目录

正文

下载分为单文件下载和多文件下载,本质没有太大区别,都是使用协程,使用UnityWebRequest开启下载,可以对UnityWebRequest做一个简单封装,代码在下面,叫WebFileRequest

public class WebFileRequest : WebRequestBase, IDisposable
{
    /// <summary>
    /// 文件存储路径
    /// </summary>
    public string SavePath { private set; get; }
    protected Action<long, float> onProgress;
    public WebFileRequest(string url, string savePath, Action<long, float> onProgressCallback=null) : base(url)
    {
        SavePath = savePath;
        onProgress = onProgressCallback;
    }
    public override IEnumerator DownLoad()
    {
        // Check fatal
        if (States != EWebRequestStates.None)
            throw new Exception($"{nameof(WebFileRequest)} is downloading yet : {URL}");

        States = EWebRequestStates.Loading;

        //获得文件下载长度
        var headRequest = UnityWebRequest.Head(URL);
        yield return headRequest.SendWebRequest();
        var totalLength = long.Parse(headRequest.GetResponseHeader("Content-Length"));

        // 下载文件
        using(var CacheRequest = UnityWebRequest.Get(URL))
        {
            using(var fs = new FileStream(SavePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                var fileLen = fs.Length;
                if (fileLen >= totalLength)
                {
                    MotionLog.Log(ELogLevel.Log, $"{SavePath} download finished {fileLen}/{totalLength}");
                    States = EWebRequestStates.Success;
                    yield break;
                }
                CacheRequest.timeout = Timeout;
                CacheRequest.downloadHandler = new DownloadHandlerFileStream(fs, 40960, fileLen, onProgress);
                CacheRequest.disposeDownloadHandlerOnDispose = true;
                if (fileLen > 0)
                {
                    MotionLog.Log(ELogLevel.Log, $"resume download {URL.Substring(URL.LastIndexOf("/"))} from: {fileLen / 1024f}KB");
                    CacheRequest.SetRequestHeader("Range", $"bytes={fileLen}-");
                    fs.Seek(fileLen, SeekOrigin.Begin);
                }
                yield return CacheRequest.SendWebRequest();
                fs.Close();
                // Check error
                if (CacheRequest.isNetworkError || CacheRequest.isHttpError)
                {
                    MotionLog.LogWarning($"Failed to download web file : {URL} Error : {CacheRequest.error}");
                    States = EWebRequestStates.Fail;
                }
                else
                {
                    States = EWebRequestStates.Success;
                }
            }
        }
    }
}

单任务下载:

IEnumerator DownloadWithSingleTask(List<PatchElement> newDownloaded)
{
    foreach (var element in newDownloaded)
    {
        string url = _patcher.GetWebDownloadURL(element.Name);
        string savePath = AssetPathHelper.MakeDownloadTempPath(element.Name);
        PatchHelper.CreateFileDirectory(savePath);
        // 创建下载器
        using (var download = new WebFileRequest(url, savePath, OnDownloadProgress))
        {
            yield return download.DownLoad();
            //PatchHelper.Log(ELogLevel.Log, $"Web file is download : {savePath}");
            // 检测是否下载失败
            if (download.States != EWebRequestStates.Success)
            {
                PatchEventDispatcher.SendWebFileDownloadFailedMsg(url, element.Name);
                failedOnDownload = true;
                yield break;
            }
        }
        currentDownloadSizeKB += element.SizeKB;
        currentDownloadCount++;
        element.SavePath = savePath;
    }
}

多任务下载:

可以自定义一次下载N个任务,在while循环中不断判断是否有任务完成,如果完成继续开启下一个任务,最后检查所有任务是否完成。


private class DownloadJob
{
    public UnityWebRequest req;
    public PatchElement info;
}

IEnumerator DownloadWithMultiTask(List<PatchElement> downloadList)
{
    var maxJobs = 5;
    var runningJobs = new List<DownloadJob>(maxJobs);
    var lastRecordTime = Time.realtimeSinceStartup;
    int assignedIdx = 0;
    while (assignedIdx < downloadList.Count)
    {
        while (runningJobs.Count < maxJobs && assignedIdx < downloadList.Count)
        {
            var element = downloadList[assignedIdx];
            var url = _patcher.GetWebDownloadURL(element.Name);
            string savePath = AssetPathHelper.MakeDownloadTempPath(element.Name);
            PatchHelper.CreateFileDirectory(savePath);

            var job = UnityWebRequest.Get(url);
            job.downloadHandler = new DownloadHandlerFile(savePath) { removeFileOnAbort = true };
            job.SendWebRequest();
            runningJobs.Add(new DownloadJob()
            {
                req = job,
                info = element
            });
            assignedIdx++;
        }                
        yield return new WaitUntil(() => CheckAnyDownloadFinished(runningJobs, ref lastRecordTime));
        if (failedOnDownload) yield break;
    }
    yield return new WaitUntil(() => CheckAllDownloadFinished(runningJobs, ref lastRecordTime));
    
    //clear up all request jobs            
    foreach(var job in runningJobs)
    {
        LogIfFailed(job);
        job.req.Dispose();
    }
    runningJobs.Clear();
}


bool CheckAnyDownloadFinished(List<DownloadJob> jobs, ref float lastRecordTime)
{
    long downloadedBytes = 0;
    int finished = 0;
    for(var i=jobs.Count-1; i>=0; i--)
    {
        var job = jobs[i];
        if(job.req.isDone)
        {
            finished++;
            LogIfFailed(job);
            jobs.RemoveAt(i);
            downloadedBytes += job.info.SizeKB;
            job.req.Dispose();
        }                
    }
    if (finished>0)
    {
        var deltaTime = Time.realtimeSinceStartup - lastRecordTime;
        currentDownloadCount += finished;
        currentDownloadSizeKB += downloadedBytes;
        OnDownloadProgress(downloadedBytes, downloadedBytes /  deltaTime);
        lastRecordTime += deltaTime;
    }
    return finished > 0;
}

bool CheckAllDownloadFinished(List<DownloadJob> jobs, ref float lastRecordTime)
{
    long downloadedBytes = 0;
    foreach(var job in jobs)
    {
        if (!job.req.isDone) return false;
        downloadedBytes += job.info.SizeKB;
    }
    var deltaTime = Time.realtimeSinceStartup - lastRecordTime;
    if(deltaTime > 0)
    {
        currentDownloadCount += jobs.Count;
        currentDownloadSizeKB += downloadedBytes;
        OnDownloadProgress(downloadedBytes, downloadedBytes / deltaTime);
        lastRecordTime += deltaTime;
    }
    return true;
}
void LogIfFailed(DownloadJob job)
{
    if (job.req.isHttpError || job.req.isNetworkError)
    {
        PatchEventDispatcher.SendWebFileDownloadFailedMsg(job.req.url, job.info.Name);
        failedOnDownload = true;
        MotionLog.LogWarning($"Failed to download file: {job.info.Name}.");
    }
}

下面是根据平台拼接下载连接的代码,请注意,除了要区分安卓和IOS平台,还要区分用户年龄版本

游戏在中国是区分8+、12+、16+的,所以为了面对不同用户群,可能会选择不同下载连接。

public string GetWebDownloadURL(string fileName)
{
    string path = $"{GetCDNServerIP()}/{fileName}";
    MotionLog.Log(ELogLevel.Log, $"path is {path}");
    return path;
}

public string GetCDNServerIP()
{
    if (RuntimePlatform.IPhonePlayer == Application.platform)
    {
        return cdnurl + "/iOS";
    }else if (RuntimePlatform.Android == Application.platform)
    {
        if (Application.identifier == "kr.co.sincetimes.gxhgkids")
        {
            return cdnurl + "/Android12";
        }
        else
        {
            return cdnurl + "/Android";
        }
    }
    else
    {
#if UNITY_ANDROID
        if (Application.identifier == "kr.co.sincetimes.gxhgkids")
        {
            return cdnurl + "/Android12";
        }
        else
        {
            return cdnurl + "/Android";
        }
#elif UNITY_IOS
        return cdnurl + "/iOS";
#else
        //return cdnurl + "/PC";
        return cdnurl + "/Android";
#endif
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Little丶Seven

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值