UniTask icon indicating copy to clipboard operation
UniTask copied to clipboard

Async method vs pure UniTask return

Open MeisterDerMagie opened this issue 9 months ago • 1 comments

Hello there!

I hope this is the right place to ask. I'm trying to understand how exactly UniTasks work.

Let's say we have this code:

private async UniTask LoadGameAsync()
{
    //this should be the right way to await the scene loading
    await LoadSceneAsync("Level_01");
    Debug.Log("Level 01 finished loading.");
    
    //does this work?
    //I'm uncertain if this is correct because I await a non async method. But then again it returns a task ... No compiler error.
    await LoadScene("Level_02");
    Debug.Log("Level 02 finished loading.");
    
    //why all this?
    //because I want to load multiple scenes simultaneously and only when all are finished loading, hide a loading screen.
    //Does this work the way I intend to or are there pitfalls to avoid? If so, what's the correct way of implementing something like this?
    UniTask level03Task = LoadScene("Level_03");
    UniTask level03UITask = LoadScene("Level_03_UI");
    await UniTask.WhenAll(level03Task, level03UITask);
    Debug.Log("Level 03 and its UI finished loading, hide loading screen now.");
}

private async UniTask LoadSceneAsync(string sceneName)
{
    await SceneManager.LoadSceneAsync(sceneName).ToUniTask();
}

private UniTask LoadScene(string sceneName)
{
    return SceneManager.LoadSceneAsync(sceneName).ToUniTask();
}

The comments in the code basically summarize my question. Is it possible to return a UniTask from a method and then await it? It somehow feels wrong because the method is basically the same as the async one but ... not async.

If this doesn't work as intended, what would be the correct way to implement what I imagine?

Thank you!

MeisterDerMagie avatar May 22 '24 15:05 MeisterDerMagie