沒意外 Addressable 將會成為開發 Unity 遊戲的必備技能,尤其是有在做手機 APP 開發的程式人。為了防止自己忘記寫法,只要有空檔就會來更新這篇 Addressable 語法筆記。
基本觀念
命名空間
1using UnityEngine.AddressableAssets;
工作流程
1. 下載資源
在使用資源前,必定要先用 LoadAsset(s)Async 系列的語法來讓他進行下載。這個工作是非同步進行的,後面會有範例程式碼。
2. 調用資源
完成下載後即可直接調用,如果沒有先下載的話系統會出錯。
資源 Key
在載入資源時都會用到 Key,這個東西其實就是 Addressable Name 和 Label。而因為 Key 可以重複指定 (用於一次下載大量資料),所以在包資源時要注意名稱不要有衝突。
LoadAssetAsync
沒有 s 的是下載單筆資源,寫法有用協程 (Coroutine)、 Async 和 Event 三種:
Coroutine
1private IEnumerator LoadCubeAsset () {
2 var cube = Addressables.LoadAssetAsync<GameObject>("Cube");
3 yield return cube;
4 Instantiate(cube.Result);
5}
Async
1private async void LoadCubeAssetAsync () {
2 var cube = Addressables.LoadAssetAsync<GameObject>("Cube");
3 await cube.Task;
4 Instantiate(cube.Result);
5}
Event
1private void LoadCubeAssetEvent () {
2 Addressables.LoadAssetAsync<GameObject>("Cube").Completed += x => Instantiate(x.Result);
3}
LoadAssetsAsync
下載多筆資源。第二個參數是一個 Action
1Addressables.LoadAssetsAsync<GameObject>("Cube", cubes.Add);
也可給他多筆 Key:
1Addressables.LoadAssetsAsync<GameObject>(new string[] { "Cube", "Profile" }, cubes.Add);
範例 (Async 寫法):
1var cubes = new List<GameObject>();
2var asyncWork = Addressables.LoadAssetsAsync<GameObject>("Cube", cubes.Add);
3await asyncWork.Task;
4
5foreach (var e in cubes)
6{
7 Debug.Log(e.name);
8}
LoadSceneAsync
場景也可以放到 Addressable 中,如果場景中存在已包好的物件,會自動全部下載,一樣要用非同步載入。
1await Addressables.LoadSceneAsync("Combat", LoadSceneMode.Additive).Task;
AssetReference
AssetReference 要在 Inspector 中指派,預設是沒有限定型別,但他有 AssetReferenceGameObject、AssetReferenceTexture 等變種,通常會用 AssetReferenceT
1public AssetReference allType;
2public AssetReferenceGameObject gameObj;
3public AssetReferenceTexture texture;
4public AssetReferenceT<TextAsset> textAsset;
範例 (Async 寫法):
1await gameObj.LoadAssetAsync<GameObject>().Task;
2gameObj.InstantiateAsync().Completed += x => {
3 x.Result.AddComponent<BoxCollider>();
4};