[Unity] Addressable v1.16.19 常用語法整理

發表日期:
2021.09.04
/
分類:
沒意外 Addressable 將會成為開發 Unity 遊戲的必備技能,尤其是有在做手機 APP 開發的程式人。為了防止自己忘記寫法,只要有空檔就會來更新這篇 Addressable 語法筆記。 基本觀念 命名

沒意外 Addressable 將會成為開發 Unity 遊戲的必備技能,尤其是有在做手機 APP 開發的程式人。為了防止自己忘記寫法,只要有空檔就會來更新這篇 Addressable 語法筆記。

基本觀念

命名空間

using UnityEngine.AddressableAssets;

工作流程

1. 下載資源

在使用資源前,必定要先用 LoadAsset(s)Async 系列的語法來讓他進行下載。這個工作是非同步進行的,後面會有範例程式碼。

2. 調用資源

完成下載後即可直接調用,如果沒有先下載的話系統會出錯。

資源 Key

在載入資源時都會用到 Key,這個東西其實就是 Addressable Name 和 Label。而因為 Key 可以重複指定 (用於一次下載大量資料),所以在包資源時要注意名稱不要有衝突。

LoadAssetAsync

沒有 s 的是下載單筆資源,寫法有用協程 (Coroutine)、 Async 和 Event 三種:

Coroutine

private IEnumerator LoadCubeAsset () {
    var cube = Addressables.LoadAssetAsync<GameObject>("Cube");
    yield return cube;
    Instantiate(cube.Result);
}

Async

private async void LoadCubeAssetAsync () {
    var cube = Addressables.LoadAssetAsync<GameObject>("Cube");
    await cube.Task;
    Instantiate(cube.Result);
}

Event

private void LoadCubeAssetEvent () {
    Addressables.LoadAssetAsync<GameObject>("Cube").Completed += x => Instantiate(x.Result);
}

LoadAssetsAsync

下載多筆資源。第二個參數是一個 Action,在下載完成一筆資料時會調用,但不保證順序。

Addressables.LoadAssetsAsync<GameObject>("Cube", cubes.Add);

也可給他多筆 Key:

Addressables.LoadAssetsAsync<GameObject>(new string[] { "Cube", "Profile" }, cubes.Add);

範例 (Async 寫法):

var cubes = new List<GameObject>();
var asyncWork = Addressables.LoadAssetsAsync<GameObject>("Cube", cubes.Add);
await asyncWork.Task;

foreach (var e in cubes)
{
    Debug.Log(e.name);
}

LoadSceneAsync

場景也可以放到 Addressable 中,如果場景中存在已包好的物件,會自動全部下載,一樣要用非同步載入。

await Addressables.LoadSceneAsync("Combat", LoadSceneMode.Additive).Task;

AssetReference

AssetReference 要在 Inspector 中指派,預設是沒有限定型別,但他有 AssetReferenceGameObject、AssetReferenceTexture 等變種,通常會用 AssetReferenceT 來自己設定。

public AssetReference allType;
public AssetReferenceGameObject gameObj;
public AssetReferenceTexture texture;
public AssetReferenceT<TextAsset> textAsset;

範例 (Async 寫法):

await gameObj.LoadAssetAsync<GameObject>().Task;
gameObj.InstantiateAsync().Completed += x => {
    x.Result.AddComponent<BoxCollider>();
};
comments powered by Disqus