Wait for asynchronous loads with events
You can add a delegate function to the Completed
event of an AsyncOperationHandle
. The operation calls the delegate function when it's finished.
The following script performs the same function as the example in Wait for asynchronous loads with coroutines, but uses an event delegate instead of a coroutine:
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
internal class LoadWithEvent : MonoBehaviour
{
public string address;
AsyncOperationHandle<GameObject> opHandle;
void Start()
{
// Create operation
opHandle = Addressables.LoadAssetAsync<GameObject>(address);
// Add event handler
opHandle.Completed += Operation_Completed;
}
private void Operation_Completed(AsyncOperationHandle<GameObject> obj)
{
if (obj.Status == AsyncOperationStatus.Succeeded)
{
Instantiate(obj.Result, transform);
}
else
{
obj.Release();
}
}
void OnDestroy()
{
opHandle.Release();
}
}
The handle instance passed to the event delegate is the same as that returned by the original method call. You can use either to access the results and status of the operation and to release the operation handle and loaded assets.