Good tutorial on using Tasks and Async

Hi,

So I’ve never used Tasks before and the unity documentation isn’t very helpful for someone new to tasks.

public async void LoadSomeData()
{
    Dictionary<string, string> savedData = await CloudSaveService.Instance.Data.LoadAsync(new HashSet<string>{"key"});

    Debug.Log("Done: " + savedData["key"]);
}

What is the best way to actually save that retrieved data? I can’t pass in a ref, in or out with async. So I am forced to pass in a reference to a class I’ve created. This doesn’t seem that elegant.

Thanks!

You can pass data in and out of an asynchronous method. To return data, use a Task.

e.g. When joining a multiplayer lobby. The QuickJoin method might look like

        public async Task<Lobby> QuickJoinLobby()
        {

            try
            {
                //return currentLobby;
                currentLobby = await Lobbies.Instance.QuickJoinLobbyAsync();
                .
                Debug.Log($"Quick Joining with code {currentLobby.Data["JoinCodeKey"].Value}"); 
                .
                .
                return currentLobby;                              
            }
            catch
            {
                Debug.Log("Quick Lobby Join Exceptions, I guess I'll create my own Lobby");
                return null;
            }
        }

And would be called with
var lobby = await networkLobby.CreateNewLobby();

Here are a couple of links that might help:

1 Like

Thank you, that C# tutorial is helpful but still a big verbose. Would love to see an example in the Unity Documentation :).

1 Like