U4S4L15——异步加载的几种使用方式
回顾目前动态异步加载的使用方式
1 2 3 4 5 6 7 8 9 10
| var handle = Addressables.LoadAssetAsync<GameObject>("Cube");
handle.Completed += (obj) => { if (handle.Status == AsyncOperationStatus.Succeeded) { print("事件创建对象"); Instantiate(obj.Result); } };
|
3种使用异步加载资源的方式
- 事件监听(目前学习过的)
- 协同程序(协程相关知识详见:协同程序)
- 异步函数(
async
和 await
,详见:异步方法)
通过协程使用异步加载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| AsyncOperationHandle<GameObject> handle;
void Start() { StartCoroutine(LoadAsset()); }
IEnumerator LoadAsset() { handle = Addressables.LoadAssetAsync<GameObject>("Cube"); if (!handle.IsDone) yield return handle; if (handle.Status == AsyncOperationStatus.Succeeded) { print("协同程序创建对象"); Instantiate(handle.Result); } else Addressables.Release(handle); }
|
输出:
通过异步函数async和await加载
注意:WebGL平台不支持异步函数语法!
单任务加载:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| AsyncOperationHandle<GameObject> handle;
void Start() { Load(); }
async void Load() { handle = Addressables.LoadAssetAsync<GameObject>("Cube"); if (!handle.IsDone) await handle.Task; if (handle.Status == AsyncOperationStatus.Succeeded) { print("异步方法创建对象"); Instantiate(handle.Result); } else Addressables.Release(handle); }
|
多任务加载:多任务加载可以使用Task.WhenAll()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| AsyncOperationHandle<GameObject> handle;
void Start() { Load(); }
async void Load() { handle = Addressables.LoadAssetAsync<GameObject>("Cube"); AsyncOperationHandle<GameObject> handle2 = Addressables.LoadAssetAsync<GameObject>("Sphere"); await Task.WhenAll(handle.Task, handle2.Task); if (handle.Status == AsyncOperationStatus.Succeeded && handle2.Status == AsyncOperationStatus.Succeeded) { print("异步方法创建多个对象"); Instantiate(handle.Result); Instantiate(handle2.Result); } else Addressables.Release(handle); }
|
输出: