Addressable下载

第一种——————————

/*
*┌────────────────────────────────┐
*│ 描   述:
*│ 类   名:UpdateAssets.cs 
*│ 创  建  人:
*└────────────────────────────────┘
*/

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.AddressableAssets;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.AddressableAssets.ResourceLocators;

namespace D_Bug{
	public class UpdateAssets : MonoBehaviour
	{
		public Image m_img;
		private List<IResourceLocator> catlogResult;
		IEnumerator Start()
        {
			var init = Addressables.InitializeAsync(false);
			yield return init;
			if(init.Status == AsyncOperationStatus.Succeeded)
            {
				var checkUpdateCatlogHandle = Addressables.CheckForCatalogUpdates(false);
				yield return checkUpdateCatlogHandle;
				if(checkUpdateCatlogHandle.Status == AsyncOperationStatus.Succeeded)
                {
					//检查更新完成
					Debug.Log("AA初始化完成并做完资源检查");
                    if (checkUpdateCatlogHandle.Result.Count > 0)
                    {
					 	var updateCatlogHandle = Addressables.UpdateCatalogs(checkUpdateCatlogHandle.Result, false);
						yield return updateCatlogHandle;
						catlogResult = updateCatlogHandle.Result;
						Addressables.Release(updateCatlogHandle);
						var downloadSize = Addressables.GetDownloadSizeAsync(catlogResult[0].Keys);
						yield return downloadSize;
						Debug.Log("获取到要下载的大小"+(float)downloadSize.Result / 1024 / 1024);
                        if (downloadSize.Result > 0)
                        {
							var downloadDependenciesHandle = Addressables.DownloadDependenciesAsync(catlogResult[0].Keys, Addressables.MergeMode.Union, false);
							while(downloadDependenciesHandle.Status == AsyncOperationStatus.None)
                            {
								Debug.Log(downloadDependenciesHandle.GetDownloadStatus().Percent);
								yield return null;
                            }
							yield return downloadDependenciesHandle;
							if(downloadDependenciesHandle.Status == AsyncOperationStatus.Succeeded)
                            {
								Debug.Log("资源下载成功辣");
								//服务器下载下版本号
                            }
                            else
                            {
								Debug.Log("爬爬!" + downloadDependenciesHandle.OperationException);
							}
							Addressables.Release(downloadDependenciesHandle);
                        }
                    }
                    else
                    {
						Debug.Log("当前已经是最新的资源乐!!");
                    }
					Addressables.LoadAssetAsync<Sprite>("0").Completed += result =>
					{
						m_img.sprite = result.Result;
					};
                }
                else
                {
					//检查更新失败
					Debug.Log("检查失败了还玩呢?" + checkUpdateCatlogHandle.OperationException);
                }
				Addressables.Release(checkUpdateCatlogHandle);
			}
			Addressables.Release(init);
        }
	}
}

第二种——————————

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.AddressableAssets.ResourceLocators;
using UnityEngine.UI;

// 检测更新并下载资源
public class CheckUpdateAndDownload : MonoBehaviour
{
    /// <summary>
    /// 显示下载状态和进度
    /// </summary>
    public Text updateText;

    /// <summary>
    /// 重试按钮
    /// </summary>
    public Button retryBtn;

    void Start()
    {
        retryBtn.gameObject.SetActive(false);
        retryBtn.onClick.AddListener(() =>
        {
            StartCoroutine(DoUpdateAddressadble());
        });

        // 默认自动执行一次更新检测
        StartCoroutine(DoUpdateAddressadble());
    }

    IEnumerator DoUpdateAddressadble()
    {
        AsyncOperationHandle<IResourceLocator> initHandle = Addressables.InitializeAsync();
        yield return initHandle;

        // 检测更新
        var checkHandle = Addressables.CheckForCatalogUpdates(true);
        yield return checkHandle;
        if (checkHandle.Status != AsyncOperationStatus.Succeeded)
        {
            OnError("CheckForCatalogUpdates Error\n" +  checkHandle.OperationException.ToString());
            yield break;
        }

        if (checkHandle.Result.Count > 0)
        {
            var updateHandle = Addressables.UpdateCatalogs(checkHandle.Result, true);
            yield return updateHandle;

            if (updateHandle.Status != AsyncOperationStatus.Succeeded)
            {
                OnError("UpdateCatalogs Error\n" + updateHandle.OperationException.ToString());
                yield break;
            }

            // 更新列表迭代器
            List<IResourceLocator> locators = updateHandle.Result;
            foreach (var locator in locators)
            {
                List<object> keys = new List<object>();
                keys.AddRange(locator.Keys);
                // 获取待下载的文件总大小
                var sizeHandle = Addressables.GetDownloadSizeAsync(keys.GetEnumerator());
                yield return sizeHandle;
                if (sizeHandle.Status != AsyncOperationStatus.Succeeded)
                {
                    OnError("GetDownloadSizeAsync Error\n" + sizeHandle.OperationException.ToString());
                    yield break;
                }

                long totalDownloadSize = sizeHandle.Result;
                updateText.text = updateText.text + "\ndownload size : " + totalDownloadSize;
                Debug.Log("download size : " + totalDownloadSize);
                if (totalDownloadSize > 0)
                {
                    // 下载
                    var downloadHandle = Addressables.DownloadDependenciesAsync(keys, true);
                    while (!downloadHandle.IsDone)
                    {
                        if (downloadHandle.Status == AsyncOperationStatus.Failed)
                        {
                            OnError("DownloadDependenciesAsync Error\n"  + downloadHandle.OperationException.ToString());
                            yield break;
                        }
                        // 下载进度
                        float percentage = downloadHandle.PercentComplete;
                        Debug.Log($"已下载: {percentage}");
                        updateText.text = updateText.text + $"\n已下载: {percentage}";
                        yield return null;
                    }
                    if (downloadHandle.Status == AsyncOperationStatus.Succeeded)
                    {
                        Debug.Log("下载完毕!");
                        updateText.text = updateText.text + "\n下载完毕";
                    }
                }
            }
        }
        else
        {
            updateText.text = updateText.text + "\n没有检测到更新";
        }

        // 进入游戏
        EnterGame();
    }

    // 异常提示
    private void OnError(string msg)
    {
        updateText.text = updateText.text + $"\n{msg}\n请重试! ";
        // 显示重试按钮
        retryBtn.gameObject.SetActive(true);
    }


    // 进入游戏
    void EnterGame()
    {
        // TODO
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值