Hi Unity Developers ,
What is the difference between the two approaches. Does both perform the download action asynchronously ?
IEnumerator LoadGameObject()
{
//Load a GameObject
AsyncOperationHandle goHandle = Addressables.LoadAssetAsync(“gameObjectKey”);
yield return goHandle;
if(goHandle.Status == AsyncOperationStatus.Succeeded)
{
GameObject obj = goHandle.Result;
//etc…
}
}
public async Task LoadGameObject()
{
//Load a GameObject
AsyncOperationHandle goHandle = Addressables.LoadAssetAsync(“gameObjectKey”);
await goHandle.Task;
if(goHandle.Status == AsyncOperationStatus.Succeeded)
{
GameObject obj = goHandle.Result;
//etc…
}
}
Cheers
There are code tags please use them when posting code.
In the way you’ve written your methods there is not much difference in execution.
There are differences between Coroutines and Asynchronous Tasks. Coroutines IEnumerators can’t return anything.
Coroutines run in MonoBehaviour context, if it gets deactivated or destroyed it kills the coroutine whereas Tasks continue to run.
So consider the following code
IEnumerator:
private IEnumerator Awake()
{
yield return StartCoroutine(LoadAsset(Initialize, () => Debug.LogError("Could not load"), "key"));
}
private IEnumerator LoadAsset(Action<GameObject> onComplete, Action onFailure, string key)
{
var handle = Addressables.LoadAssetAsync<GameObject>(key);
yield return handle;
switch (handle.Status)
{
case AsyncOperationStatus.Succeeded:
onComplete.Invoke(handle.Result);
break;
case AsyncOperationStatus.Failed:
onFailure.Invoke();
break;
}
}
private void Initialize(GameObject obj) => obj.SetActive(false);
Async Task:
public class ExampleClass : MonoBehaviour
{
private async void Awake()
{
var asset = await Addressables.LoadAssetAsync<GameObject>("key").Task;
if(asset != null) Initialize(asset);
else Debug.LogError("Could not load");
}
private void Initialize(GameObject obj) => obj.SetActive(false);
}
I replaced coroutines with Tasks throughout my projects. But they come with a few caveats though.
You’d have to make sure you’re running code on the main thread because you can’t call any Unity related methods outside the main thread.
Tasks continue to run even if you destroyed the object or even when going out of play mode in the editor.
Tasks can’t easily be killed you’ll need a CancellationToken which makes code a bit more complicated again.
There are more differences and they both have their pro’s and con’s. The biggest issue I have with coroutines is that they can’t return a value.
3 Likes
Thanks @MaskedMouse for the right explanation , now i understood better.