Addressable:7、异步操作处理(Async operation handling)

你。 提交于 2020-01-18 14:47:27

Addressables API的几种方法返回一个AsyncOperationHandle结构。此句柄的主要目的是允许访问操作的状态和结果。在您调用Addressables.Release或Addressables.ReleaseInstance进行该操作之前,该操作的结果是有效的(有关释放资源的更多信息,请参阅有关内存管理的文档)。

操作完成后,AsyncOperationHandle.Status属性为AsyncOperationStatus.Succeeded或AsyncOperationStatus.Failed。如果成功,则可以通过AsyncOperationHandle.Result属性访问结果。
您可以定期检查操作状态,也可以使用AsyncOperationHandle.Complete事件注册完成的回调。当不再需要返回的AsyncOperationHandle结构提供的资源时,应使用方法释放它Addressables.Release

1、类型与无类型的句柄(Type vs. typeless handles)

大多数Addressables API方法都返回通用AsyncOperationHandle结构,从而为AsyncOperationHandle.Completed事件和AsyncOperationHandle.Result对象提供类型安全性。还有一个非泛型AsyncOperationHandle结构,您可以根据需要在两个句柄之间进行转换。

请注意,如果尝试将非泛型句柄强制转换为错误类型的泛型句柄,则会发生运行时异常。例如:
AsyncOperationHandle<Texture2D> textureHandle = Addressables.LoadAssetAsync<Texture2D>("mytexture");

// Convert the AsyncOperationHandle<Texture2D> to an AsyncOperationHandle:
AsyncOperationHandle nonGenericHandle = textureHandle;

// Convert the AsyncOperationHandle to an AsyncOperationHandle<Texture2D>:
AsyncOperationHandle<Texture2D> textureHandle2 = nonGenericHandle.Convert<Texture2D>();

// This will throw and exception because Texture2D is required:
AsyncOperationHandle<Texture> textureHandle3 = nonGenericHandle.Convert<Texture>();

2、AsyncOperationHandle 示例

使用AsyncOperationHandle.Completed回调为完成事件注册侦听器:
private void TextureHandle_Completed(AsyncOperationHandle<Texture2D> handle) {
    if (handle.Status == AsyncOperationStatus.Succeeded) {
        Texture2D result = handle.Result;
        // The texture is ready for use.
    }
}

void Start() {
    AsyncOperationHandle<Texture2D> textureHandle = Addressables.LoadAsset<Texture2D>("mytexture");
    textureHandle.Completed += TextureHandle_Completed;
}
AsyncOperationHandle实现IEnumerator,因此可以在协程中使用:
public IEnumerator Start() {
    AsyncOperationHandle<Texture2D> handle = Addressables.LoadAssetAsync<Texture2D>("mytexture");
    yield return handle;
    if (handle.Status == AsyncOperationStatus.Succeeded) {
        Texture2D texture = handle.Result;
        // The texture is ready for use.
        // ...
    // Release the asset after its use:
        Addressables.Release(handle);
    }
}
Addressables还通过AsyncOperationHandle.Task属性支持异步await:
public async Start() {
    AsyncOperationHandle<Texture2D> handle = Addressables.LoadAssetAsync<Texture2D>("mytexture");
    await handle.Task;
    // The task is complete. Be sure to check the Status is successful before storing the Result.
}

AsyncOperationHandle.Task属性在WebGL上不可用,因为该平台不支持多线程操作。
请注意,加载场景使用SceneManager.LoadSceneAsync并将allowSceneActivation参数设置为false或使用Addressables.LoadSceneAsync并将activateOnLoad参数设置为false,会导致随后的异步操作被阻塞并且无法完成。请阅读allowSceneActivation文档

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!