Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Async method vs pure UniTask return #587

Closed
MeisterDerMagie opened this issue May 22, 2024 · 1 comment
Closed

Async method vs pure UniTask return #587

MeisterDerMagie opened this issue May 22, 2024 · 1 comment

Comments

@MeisterDerMagie
Copy link

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!

@timcassell
Copy link

https://blog.stephencleary.com/2016/12/eliding-async-await.html

Give that a read, and just replace Task with UniTask.

@neuecc neuecc closed this as completed Oct 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants