Unity Gaming Services tutorial series, part 2: Player login

Welcome back to the Unity Gaming Services (UGS) tutorial series. In this second post in the series, we’ll look at player login methods with Unity Player Accounts. Identifying the user will be key since all of the other services will connect to player identities or IDs.

Where to find all of the content in the Unity Gaming Services tutorial series

The UGS series consists of 10 sets of tutorials, with each set comprising a video and written tutorial.

Video tutorials

The full video tutorial series will be here. We’ll add the video tutorials to this playlist throughout October.

Written tutorials

You’ll find links to all articles in this series as they become available in Part 1, the introduction post.

Demo project and scripts

You can find the Gem Hunter Match – Cloud Edition demo project in the GitHub page.

The scripts used in the tutorials can be downloaded here:
UGSTutorialSeries_Scripts.zip (1.6 MB)

You can watch the video version of this tutorial here:

Set up player ID with Unity Player Accounts

Player IDs are the player’s unique identification used by all gaming services, providing features like cloud data, friends, or leaderboards. In order to do that, a player will be signed in anonymously and a Player ID will be created if there was not an existing Player ID token in the cache.

However, games as a service are long-lasting experiences that players play from different devices, often over the span of several years. With identity providers, you’ll be able to retrieve the player’s Player ID, providing them with a consistent gameplay experience across different devices.

Let’s get familiar with the Unity Dashboard, starting with how a player can quickly sign in to get his Player ID, and how to retrieve the ID later with Unity’s identity provider capabilities via Unity Player Accounts. Upcoming tutorials will show you how to integrate other identity providers like Facebook, Google Play Games, and Apple Game Center. We’ll conclude by testing if the player’s information/settings are correctly stored/saved via Unity Cloud Save Player Data.

Player ID Anonymous sign-in Identity provider sign-in
The player’s unique identification used by all gaming services If it’s the first sign-in, a new Player ID will be created, This is a guest sign-in where the Player ID is only linked to the current device. If the first sign-in is with an identity provider, a new Player ID will be created, and this ID will be linked to the identity provider and recoverable.
This quick method should be the default method to sign back in a player to start using gaming services. Identity providers are meant to be used for the first sign-in or to be linked to later.

The Unity Dashboard

Start by creating a new project from the Unity Hub; enable Connect to Unity Cloud with the new project.

Once the project has been created, go to cloud.unity.com and in the top left of the side menu, select Projects > UGSTutorialSeries (Click the + icon to the right of the Shortcuts option to see all of the services you can add to your project).

Go to Products > Player Authentication > Launch (you can click on Learn more to get an introduction to each service).

From here, click Add Identity Provider, then select Unity Player Accounts, which is integrated into Unity and offers a way to recover a player ID.

When you add Unity Player Accounts, you will be asked what platform to support; enable PC to make sure you can also test in the Unity Editor.

Note: We recommend that you go through this checklist before publishing your project to make sure you’re complying with the Unity Player Account guidelines.

The last step to get your project using login methods will be to install the Authentication package from the Package Manager.

Under Project Settings > Services, you’ll find the Authentication package options and Unity Player Accounts previously added from the Unity Dashboard. You can always add other third-party identity providers from Project Settings or your Unity Dashboard.

From here, you’ll get all the steps you need to implement an anonymous sign-in and a recoverable Unity Player Account login.

Anonymous sign-in

The first method that you’ll implement is signing in as a guest. This is the most frictionless method to start with; some games default to this sign-in method so players can start playing the game quickly and then later offer the option for players to link their accounts to a provider.


From GHM – CE: The first-time sign-in screen, left, and center and right, additional sign-in options provided later in the game

In mobile games, you’ll frequently get a login screen first, offering options for both playing as a guest or retrieving your account; in the context of UGS, these are referred to as anonymous and provider logins.

A first-time sign-in will create a Player ID and session token. If the first-time sign-in was made with an identity provider, the newly created Player ID will automatically be linked to the identity provider. See this flow represented in the following diagram.

Let’s create a simple project to try this feature. Start by adding some UI buttons in the Scene view via the top-menu GameObject > UI > Button-TextMeshPro for the different login methods. For now you only need Anonymous and Unity.

Then create an empty GameObject in the Hierarchy called LoginManager and add an empty script component to it with the same name – LoginManager.

Create a method in LoginManager to sign in anonymously; here is the code example from UGS documentation.

using System.Threading.Tasks;
using Unity.Services.Authentication;
using Unity.Services.Core;
using UnityEngine;

public class LoginManager : MonoBehaviour
{
    private async void Awake()
    {
        if (UnityServices.State == ServicesInitializationState.Uninitialized)
        {
            Debug.Log("Services Initializing");
            await UnityServices.InitializeAsync();
        }
    }

    private async void Start()
    {
    }
    public async void StartAnonymousSignIn()
    {
        await SignInAnonymouslyAsync();
    }

    private async Task SignInAnonymouslyAsync()
    {
        try
        {
            await AuthenticationService.Instance.SignInAnonymouslyAsync();
            Debug.Log("Sign in anonymously succeeded!");

            // Shows how to get the playerID
            Debug.Log($"PlayerID: {AuthenticationService.Instance.PlayerId}");

        }
        catch (AuthenticationException ex)
        {
            // Compare error code to AuthenticationErrorCodes
            // Notify the player with the proper error message
            Debug.LogException(ex);
        }
        catch (RequestFailedException ex)
        {
            // Compare error code to CommonErrorCodes
            // Notify the player with the proper error message
            Debug.LogException(ex);
        }
    }
}

Notes on the code:

  • To use async Tasks required by the services you need to add using System.Threading.Tasks; at the beginning of the script.
  • On Awake(), initialize UnityServices if they are not already initialized.
  • Create a wrapper method StartAnonymousSignIn() to use with the UI button.

On the Anonymous button, assign the following method to the OnClick event.

Press Play and in the Console you’ll see the Player ID of the successfully signed-in player, with the player authenticated and ready to be used in other Unity services.
Unity Gaming Services series part 2_Console_successful login

Find this player in the Unity Dashboard under Player Management. Note that since this is an anonymous account, you’ll see None under Linked Identities.

Unity Player Accounts

So far you’ve signed in a player anonymously, but there’s no way to recover the account if the player loses access to the device. Because the player was first signed in anonymously you need to link an identity provider. While this tutorial covers the case for the first sign-in anonymously, the following table reflects the flow that your project should implement to allow players to recover their accounts.

First sign-in Anonymous Identity provider A
Linked identity provider None: You need to offer the player the option to link an identity provider. Identity provider A: You can give the option to the player to link additional identity providers.
Returning players You sign them in with anonymous sign-in. You sign them in with anonymous sign-in.

Previously, you added the Unity Player Accounts as the identity provider from the Unity Dashboard; as it comes with the Authentication package, no additional installation is needed.

In your project, you need a way to know if the player is signed in or not, and if they’re signed in, if it’s with a Unity Player Account (or Unity ID). Create the following method to add in the LoginManager; the StartUnitySIgnInAsync method will be accessed from the UI Button.

public async void StartUnitySignInAsync()
    {
        if (PlayerAccountService.Instance.IsSignedIn)
        {
            SignInOrLinkWithUnity();
            return;
        }

        try
        {
            await PlayerAccountService.Instance.StartSignInAsync();
        }
        catch (RequestFailedException ex)
        {
            Debug.LogException(ex);
        }
    }

Notes on the code:

  • If the player signed in, the Unity Player Account browser window should display a credential (PlayerAccountService.Instance.AccessToken) as available to use by your SignInOrLinkWithUnity method to handle the rest of the process.
  • If the player is not signed in, initialize the sign-in process by launching the Unity Player Accounts web window with PlayerAccountService.Instance.StartSignInAsync.


The sign-in flow with Unity Player Accounts on a desktop

Now let’s handle the different scenarios after the browser-based Unity Player Accounts sign-in has succeeded and the access token is available.

async void SignInOrLinkWithUnity()
    {
        try
        {
            // 1. Player is not yet authenticated, signing up with Unity
            if (!AuthenticationService.Instance.IsSignedIn)
            {
                Debug.Log("Signing up with Unity Player Account...");
                await AuthenticationService.Instance.SignInWithUnityAsync(PlayerAccountService.Instance.AccessToken);
                Debug.Log("Successfully signed up with Unity Player Account");
                return;
            }

            // 2. Player is authenticated, but does not yet have a Unity ID, so let's link
            if (!HasUnityID())
            {
                Debug.Log("Linking anonymous account to Unity...");
                await LinkWithUnityAsync(PlayerAccountService.Instance.AccessToken);
                Debug.Log("Successfully linked anonymous account!");
                return;
            }

            // 3. Player has authentication and a Unity ID
            Debug.Log("Player is already signed in to their Unity Player Account");
        }
        catch (RequestFailedException ex)
        {
            Debug.LogException(ex);
        }
    }

    private bool HasUnityID()
    {
        return AuthenticationService.Instance.PlayerInfo.GetUnityId() != null;
    }

Notes on the code:

  • If the player is not yet signed in, you can do this in the authentication service with Unity Player Accounts and the token saved; add the SignInWithUnity method to your LoginManager and then exit the method with return once it’s done.
  • If the player is already authenticated but the Unity ID is null, you’ll need to add the LinkWithUnity method; you also need to provide the token, and the method will exit after this is completed.
  • If the code is executed to this point, that means that the player is already authenticated and linked to Unity Player Accounts.

Now click on the Unity button and sign in or link with Unity Player Accounts.

Press Play, click the button, and see how the account was linked (in this case you first signed in anonymously).

Observe as well how the identity provider appears as Linked Identity under the Player Management section in the dashboard.

In addition to these methods, you can offer options to Unlink Player Accounts, sign out users, clear session tokens or delete accounts.

In the following tutorials you’ll get all the steps for integrating other identity providers, such as Facebook for iOS and Android, Google Play Games for Android devices, and Apple Game Center for iOS devices.

If you want to follow each of these tutorials in video format, don’t miss the Unity Game Services tutorial series playlist on YouTube.

2 Likes