Search code examples
c#unity-game-engine

Is it possible to load resources in Unity with async/await?


Is it possible in Unity to do something like this?

private async void LoadSomethingAsync()
{
    AudioClip clip = await Resources.LoadAsync<AudioClip>("path");
}

I know I could use Unitys Coroutines instead, but they have multiple downsides why I would like to use something like the code above.
On the internet I didn't found something that works for me either, so maybe someone of you knows if something like the code above is possible or not.


Solution

  • I've never used Addressables, but here is some relevant documentation:

    Addressables also supports asynchronous await through the AsyncOperationHandle.Task property:
    
    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. 
    }
    

    So to me it seems like you could switch to using Addressables, then do this:

    private async void LoadSomethingAsync()
    {
        AsyncOperationHandle<AudioClip> handle = Addressables.LoadAssetAsync<AudioClip>("path");
        await handle.Task;
        if (handle.Status == AsyncOperationStatus.Succeeded) 
        {
            AudioClip clip = handle.Result;
            // use clip here
        }
        else 
        {
            // handle loading error
        }
    }
    

    Note that according to the documentation, this particular solution is not available on WebGL. This may not matter to you:

    The AsyncOperationHandle.Task property is not available on WebGL as multi-threaded operations are not supported on that platform.