Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Question Good tutorial on using Tasks and Async

Discussion in 'Cloud Save' started by 8bitgoose, Sep 26, 2022.

  1. 8bitgoose

    8bitgoose

    Joined:
    Dec 28, 2014
    Posts:
    437
    Hi,

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

    Code (CSharp):
    1. public async void LoadSomeData()
    2. {
    3.     Dictionary<string, string> savedData = await CloudSaveService.Instance.Data.LoadAsync(new HashSet<string>{"key"});
    4.  
    5.     Debug.Log("Done: " + savedData["key"]);
    6. }
    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!
     
  2. Laurie-Unity

    Laurie-Unity

    Unity Technologies

    Joined:
    Mar 5, 2020
    Posts:
    169
    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
    Code (CSharp):
    1.         public async Task<Lobby> QuickJoinLobby()
    2.         {
    3.  
    4.             try
    5.             {
    6.                 //return currentLobby;
    7.                 currentLobby = await Lobbies.Instance.QuickJoinLobbyAsync();
    8.                 .
    9.                 Debug.Log($"Quick Joining with code {currentLobby.Data["JoinCodeKey"].Value}");
    10.                 .
    11.                 .
    12.                 return currentLobby;                              
    13.             }
    14.             catch
    15.             {
    16.                 Debug.Log("Quick Lobby Join Exceptions, I guess I'll create my own Lobby");
    17.                 return null;
    18.             }
    19.         }
    And would be called with
    var lobby = await networkLobby.CreateNewLobby();


    Here are a couple of links that might help:
     
  3. 8bitgoose

    8bitgoose

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