Unity Gaming Services

These are code examples are copied from some of Unity's Gaming Services. I use these example methods throughout EasyCode docs especially when describing use cases for Dynamic Async events

    public async Task GetJoinedLobbies()
    {
        try
        {
            var lobbyIds = await LobbyService.Instance.GetJoinedLobbiesAsync();
        }
        catch (LobbyServiceException e)
        {
            Debug.Log(e);
        }
    }

    public async Task RemovePlayerFromLobby()
    {
        try
        {
            //Ensure you sign-in before calling Authentication Instance
            //See IAuthenticationService interface
            string playerId = AuthenticationService.Instance.PlayerId;
            await LobbyService.Instance.RemovePlayerAsync("lobbyId", playerId);
        }
        catch (LobbyServiceException e)
        {
            Debug.Log(e);
        }
    }

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

            Debug.Log("Done: " + savedData["key"]);
        }
        catch (LobbyServiceException e)
        {
            Debug.Log(e);
        }
    }

    public async Task SavePlayerData()
    {
        try
        {
            var data = new Dictionary<string, object> { { "key", "someValue" } };
            await CloudSaveService.Instance.Data.ForceSaveAsync(data);
        }
        catch (Exception e)
        {
            Debug.Log(e);
        }
    }

    public async Task UpdatePlayerData()
    {
        try
        {
            UpdatePlayerOptions options = new UpdatePlayerOptions();

            options.Data = new Dictionary<string, PlayerDataObject>()
            {
                {
                    "existing data key", new PlayerDataObject(
                        visibility: PlayerDataObject.VisibilityOptions.Private,
                        value: "updated data value")
                },
                {
                    "new data key", new PlayerDataObject(
                        visibility: PlayerDataObject.VisibilityOptions.Public,
                        value: "new data value")
                }
            };

            //Ensure you sign-in before calling Authentication Instance
            //See IAuthenticationService interface
            string playerId = AuthenticationService.Instance.PlayerId;

            var lobby = await LobbyService.Instance.UpdatePlayerAsync("lobbyId", playerId, options);

        }
        catch (LobbyServiceException e)
        {
            Debug.Log(e);
        }
    }

Last updated