基本設(shè)置
Profile文件中配置資源構(gòu)建路徑和資源首次加載路徑,資源如何設(shè)置了緩存,在首次加載之后會(huì)將再用緩存在緩存目錄,后面將直接從緩存目錄中讀取,方便項(xiàng)目發(fā)包時(shí)候進(jìn)行使用
AddressableAssetSettings文件
DisableCatalogUpdateOnStartup 勾選改選項(xiàng),禁止自動(dòng)更新,項(xiàng)目資源下載一般需要提示玩家下載資源大小和下載進(jìn)度,需要通過(guò)代碼進(jìn)行手動(dòng)下載更新
BuildRemoteCatalog 創(chuàng)建遠(yuǎn)端資源的catalog,用于熱更新資源
設(shè)置BuildPath和 LoadPath
根據(jù)自身網(wǎng)絡(luò)狀況設(shè)置資源最大的請(qǐng)求數(shù)和下載超時(shí)時(shí)間
Group文件注意設(shè)置BundleMode ,是否將group內(nèi)的資源分散打包
Remote資源緩存
unity自身默認(rèn)緩存路徑是 C:\Users\admin\AppData\LocalLow\Unity
Addressable默認(rèn)緩存路徑 C:\Users\admin\AppData\LocalLow\Unity\項(xiàng)目名稱_AdressableLoad
可以指定遠(yuǎn)端遠(yuǎn)端資源在本地緩存路徑,需要注意的是,如果項(xiàng)目剛開(kāi)始運(yùn)行的時(shí)候沒(méi)有手動(dòng)設(shè)置緩存目錄,在手動(dòng)添加緩存目錄之后默認(rèn)緩存目錄中已經(jīng)存在的資源并不會(huì)被釋放,每次加載讀取的時(shí)候,先從手動(dòng)設(shè)置的緩存目錄中查找,在從默認(rèn)緩存中查找,如果默認(rèn)緩存中存在資源,則不會(huì)重新進(jìn)行下載
創(chuàng)建CacheInitializationSettings文件,然后將改文件關(guān)聯(lián)到AddressableAssetSettings的inititalizationObjects中,方法如下
手動(dòng)設(shè)置緩存路徑(如下圖所示方式會(huì)緩存在工程根目錄的AAAAAAA文件夾內(nèi),也可設(shè)置為 persistentDataPath 格式為{UnityEngine.Application.persistentDataPath})
每一個(gè)下載下來(lái)的bundle資源,會(huì)被緩存為_(kāi)data 和_info兩個(gè)文件,(猜測(cè):_info是索引文件信息,_data是資源序列化內(nèi)容)
代碼部分
資源下載檢測(cè)
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
public class AddressableManager : MonoBehaviour
{
public static AddressableManager instance;
List<object> keys;//addressable ×ê?′μ?label?ˉo?£?ò?°?í?ò?ààDíμ?×ê?′ó?ò???label
AsyncOperationStatus checkStatus;
long totalDownloadSize = 0;
public event Action<AsyncOperationStatus> onCheckFinish;
// Start is called before the first frame update
private void Awake()
{
instance = this;
DontDestroyOnLoad(this.gameObject);
}
public IEnumerator CheckUpadate()
{
keys = new List<object>();
totalDownloadSize = 0;
yield return Addressables.InitializeAsync();
Debug.Log("初始化檢測(cè)更新");
var checkHandle = Addressables.CheckForCatalogUpdates(false);//false是手動(dòng)釋放異步結(jié)果對(duì)象
yield return checkHandle;
Debug.Log("catalogs chek res:" + checkHandle.Status);
if(checkHandle.Status == UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationStatus.Succeeded)
{
List<string> catalogs = checkHandle.Result;
if(catalogs != null && catalogs.Count > 0)
{
var updateHandle = Addressables.UpdateCatalogs(catalogs, false);
yield return updateHandle;
var catlogResult = updateHandle.Result;
int idx = 0;
foreach (var item in catlogResult)
{
// var itemKeys = new List<object> { item.Keys };
// for (int i = 0; i < itemKeys.Count; i++)
// {
// Debug.Log($"index:{idx},key:{itemKeys[i]}");
// }
foreach (var key in item.Keys)
{
if (key is string)
{
// if (!itemKeys.Any(x => x == key.ToString()))
keys.Add(key.ToString());
}
}
}
// keys = new List<object> { catlogResult[0].Keys };
Debug.Log("updatehandle res:" + updateHandle.Status);
Debug.Log("updatehandle res:" + keys[0].ToString());
if (updateHandle.Status == UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationStatus.Succeeded)
{
var sizeHandle = Addressables.GetDownloadSizeAsync(keys);
yield return sizeHandle;
if(sizeHandle.Status == UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationStatus.Succeeded)
{
totalDownloadSize = sizeHandle.Result;
Debug.Log("下載資源大小" + (totalDownloadSize / 1024.0f / 1024.0f).ToString("0.00"));
checkStatus = AsyncOperationStatus.Succeeded;
CheckForUpdate();
}
else
{
checkStatus = AsyncOperationStatus.Failed;
CheckForUpdate();
}
Addressables.Release(sizeHandle);
}
else
{
Debug.Log("?ì2a?üD?ê§°ü£????ì2éí???×′??");
checkStatus = AsyncOperationStatus.Failed;
CheckForUpdate();
}
Addressables.Release(updateHandle);
}
else
{
Debug.Log("不需要更新catlog");
keys.Add("HD");
keys.Add("Movie");
var sizeHandel = Addressables.GetDownloadSizeAsync(keys);
yield return sizeHandel;
if(sizeHandel.Status == AsyncOperationStatus.Succeeded)
{
totalDownloadSize = sizeHandel.Result;
Debug.Log("下載資源大小" + (totalDownloadSize / 1024.0f / 1024.0f).ToString("0.00"));
checkStatus = AsyncOperationStatus.Succeeded;
CheckForUpdate();
}
else
{
Debug.Log("資源大小獲取失敗");
checkStatus = AsyncOperationStatus.Failed;
CheckForUpdate();
}
Addressables.Release(sizeHandel);
}
}
}
void CheckForUpdate()
{
if(checkStatus == AsyncOperationStatus.Succeeded && totalDownloadSize > 0)
{
StartCoroutine(ExcuteUpdate());
}else onCheckFinish?.Invoke(checkStatus);
}
IEnumerator ExcuteUpdate()
{
var downloadDependenciesHandle = Addressables.DownloadDependenciesAsync(keys, Addressables.MergeMode.Union, false);//Addressables.DownloadDependenciesAsync(keys, false);
while (downloadDependenciesHandle.Status == AsyncOperationStatus.None)
{
Debug.Log("當(dāng)前下載進(jìn)度:" + downloadDependenciesHandle.GetDownloadStatus().Percent);
yield return null;
}
if (downloadDependenciesHandle.Status == AsyncOperationStatus.Succeeded)
{
Debug.Log("download success");
}
else Debug.Log("download failed");
Addressables.Release(downloadDependenciesHandle);
onCheckFinish?.Invoke(checkStatus);
}
/// <summary>
/// ??è?μ¥??key??ó|×ê?′????′óD?
/// </summary>
/// <param name="key"></param>
/// <param name="onComplete"></param>
/// <param name="onfailed"></param>
public void GetDownloadSize(object key, Action<long> onComplete, Action onfailed = null)
{
var sizeHandle = Addressables.GetDownloadSizeAsync(key.ToString());
sizeHandle.Completed += (result) => {
if (result.Status == AsyncOperationStatus.Succeeded)
{
var downloadSize = result.Result;
onComplete?.Invoke(downloadSize);
}
else onfailed?.Invoke();
Addressables.Release(sizeHandle);
};
}
public AsyncOperationHandle Download(object key, Action onComplete, Action onFailed = null)
{
var downloadHandle = Addressables.DownloadDependenciesAsync(key.ToString(), true);
downloadHandle.Completed += (result) => {
if (result.Status == AsyncOperationStatus.Succeeded)
{
onComplete?.Invoke();
}
else onFailed?.Invoke();
};
return downloadHandle;
}
}
資源加載
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
public class AssetManager : MonoBehaviour
{
public AssetReference assetReference;
[AssetReferenceUILabelRestriction("HD")]
public AssetReference assetReferenceHD;
public AssetReferenceGameObject assetReferenceGameObject;
public AssetReferenceT<Texture> textureAsset;
//private void Awake()
//{
// Debug.Log("");
//}
void Start()
{
//AsyncOperationHandle<GameObject> res = assetReferenceGameObject.LoadAssetAsync();
//res.Completed += Res_Completed;
DontDestroyOnLoad(this.gameObject);
// LoadByName("Prefab1");
AddressableManager.instance.onCheckFinish += Instance_onCheckFinish;
StartCoroutine(AddressableManager.instance.CheckUpadate());
}
private void Instance_onCheckFinish(AsyncOperationStatus status)
{
Debug.Log("finish status is " + status);
Debug.Log("Path is " + Application.persistentDataPath);
if (status == AsyncOperationStatus.Succeeded)
{
LoadByName("Prefab3");
LoadByName("SD");//prefab2
InstantitateByName("Prefab4");
}
}
private void Res_Completed(AsyncOperationHandle<GameObject> obj)
{
if (obj.Status == AsyncOperationStatus.Succeeded)
{
GameObject gob = Instantiate(obj.Result);
Transform parent = GameObject.Find("Canvas").GetComponent<Transform>();
gob.transform.SetParent(parent);
}
}
private void LoadByName(string name)
{
Addressables.LoadAssetAsync<GameObject>(name).Completed += (handle) => {
if (handle.Status == AsyncOperationStatus.Succeeded)
{
GameObject gob = Instantiate(handle.Result, GameObject.Find("Canvas").GetComponent<Transform>());
Debug.Log($"加載資源完畢:{gob.name}");
}else Debug.Log($"加載資源失敗:{name}");
};
}
private void InstantitateByName(string name)
{
Addressables.InstantiateAsync(name).Completed += (handle) => {
if (handle.Status == AsyncOperationStatus.Succeeded)
{
GameObject gob = handle.Result;
gob.transform.SetParent(GameObject.Find("Canvas").GetComponent<Transform>());
gob.GetComponent<RectTransform>().anchoredPosition = Vector2.zero;
Debug.Log("實(shí)例化對(duì)象創(chuàng)建完畢" + gob.name);
}else Debug.Log($"加載資源失敗:{name}");
};
}
}
配置文件文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-472716.html
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ConfigManager
{
public static string CdnUrl = "http://192.168.133.144/Files/dev";
//public static string RemoteCachePath { get { return Application.persistentDataPath + "/android"; } }
public static string RemoteCachePath { get {
#if UNITY_EDITOR
return "AddresableAsset/android";
#else
return Application.persistentDataPath+"/AddresableAsset";
#endif
}
}
}
參考工程 https://gitee.com/tygkcsc/addressable-demo/tree/master文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-472716.html
到了這里,關(guān)于Unity之Addressable使用注意事項(xiàng)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!