In this article, we’ll learn how to use PlayFab’s user authentication features with user interface (UI) elements inside Unity. We’ll build on the start of our Unity game project from the first part of this series, and add the ability for users to create a new game account or login with an existing account using PlayFab.
Let’s take the Unity game project from the previous series and add user login and account creation capabilities with PlayFab.
Requirements
You’ll need a PlayFab account and the following software to follow this tutorial:
Mission Briefing
User accounts and login give players a unique identity in online games and are the first steps to building a rich set of multiplayer experiences. PlayFab makes this possible without the need to deploy or maintain any servers or databases ourselves. In this article, we’ll add account registration and login as part of the user flow to let players identify who they are on the multiplayer service.
Updating the Intro Scene with Login UI Elements
We’ll start by placing the UI elements we need into the IntroMenu scene for the player to log in or create an account.
If you’re following along using the FPS Microgame, expand the project files to FPS > Scenes, then double-click the IntroMenu scene file to load it into the editor.
Click the Game tab to put the menu scene properly into focus.
We’ll add three input fields to the canvas for the player to enter: their username, email address, and password. PlayFab doesn’t require both an email address and username, but this field will allow us to add an option in the future for our players to reset their passwords if they want.
We right-click Canvas and select UI > Input Field to place an input element in the center of the menu screen. Name or rename the element to a name like "UsernameField" so that it’s easy to find.
We repeat these steps until we have all three fields in the Hierarchy.
Next, we adjust the position of the fields so that they don’t overlap and hide each other. We click the Username Input field and set the Pos Y value to 60, select the Email input field, and set its Pos Y value to 30 so that we’ve stacked all three input fields on top of each other.
Then, we expand each input field and select Placeholder to edit the placeholder text of each to match the field.
Next, we select each input field and change the Content Type to match the type of input it needs. The Username field should be set to Alphanumeric, the Email field should be set to Email Address, and the Password field should be set to Password. This ensures the input fields have proper validation and the password text isn’t visible on the screen when the player types it in.
Let’s save our progress before continuing!
Now, let’s add two buttons by right-clicking on Canvas and selecting UI > Button to create a new button. Give each button a descriptive name such as "RegisterButton" and "LoginButton."
We want to resize and reposition the buttons so that they show below the input fields.
Here are the values used in the screenshot below:
- RegisterButton:
- Pos X: -40
- Pos Y: -30
- Width: 80
- LoginButton:
- Pos X: 40
- Pos Y: -30
- Width: 80
We expand the button elements and update the text for each so that the user knows which button to press.
We also need a text element to show any error messages resulting from the account creation and login process. So, we add a text element to the canvas by right-clicking Canvas and selecting UI > Text, and naming the element "ErrorMessage."
We position it below the buttons with Pos Y at 60 and update the text to "Error Message" for clarity.
Let’s center the text using the Paragraph > Alignment buttons and change the text to a red color for better visibility.
Also, let’s set the Vertical Overflow property to Overflow so that long error messages will also appear before the buttons.
Last, let’s hide the big Play button at the bottom of the scene from this menu so that players must register or log in to play the game.
We select the StartButton element and clear the box to the left of the element name to deactivate it.
Adding Code to the UI
We can now attach some code to those UI elements to make them active.
We create a new folder called Scripts inside the Assets folder, which is different from the one already inside the FPS folder.
We right-click on the new Scripts folder and then click Create > C# Script to add a new script file. Let’s call it "PlayFabCode."
Now, we double-click the script file to open it in Visual Studio, where we can edit the C# code.
This file contains placeholder methods for Start
and Update
.
At the top, we add the following using
statements:
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using PlayFab;
using PlayFab.ClientModels;
Inside the PlayFabCode
class, we define these variables that map to the UI elements:
public InputField Username, Email, Password;
public Text ErrorMessage;
public string SceneName = "";
We clear the ErrorMessage
text at the beginning of the game by modifying the Start
method:
void Start()
{
ErrorText.text = "";
}
Now we can add some methods to call PlayFab’s account registration API with this code:
public void RegisterClick()
{
var register = new RegisterPlayFabUserRequest { Username = Username.text, Email = Email.text, Password = Password.text };
PlayFabClientAPI.RegisterPlayFabUser(register, OnRegisterSuccess, OnRegisterFailure);
}
private void OnRegisterSuccess(RegisterPlayFabUserResult result)
{
ErrorMessage.text = "";
SceneManager.LoadScene(SceneName);
}
private void OnRegisterFailure(PlayFabError error)
{
if (error.ErrorDetails != null && error.ErrorDetails.Count > 0)
{
using (var iter = error.ErrorDetails.Keys.GetEnumerator())
{
iter.MoveNext();
string key = iter.Current;
ErrorMessage.text = error.ErrorDetails[key][0];
}
}
else
{
ErrorMessage.text = error.ErrorMessage;
}
}
And we can duplicate and modify these methods into the following code to handle logging in with PlayFab.
public void LoginClick()
{
var login = new LoginWithPlayFabRequest { Username = Username.text, Password = Password.text };
PlayFabClientAPI.LoginWithPlayFab(login, OnLoginSuccess, OnLoginFailure);
}
private void OnLoginSuccess(LoginResult result)
{
ErrorMessage.text = "";
SceneManager.LoadScene(SceneName);
}
private void OnLoginFailure(PlayFabError error)
{
if (error.ErrorDetails != null && error.ErrorDetails.Count > 0)
{
using (var iter = error.ErrorDetails.Keys.GetEnumerator())
{
iter.MoveNext();
string key = iter.Current;
ErrorMessage.text = error.ErrorDetails[key][0];
}
}
else
{
ErrorMessage.text = error.ErrorMessage;
}
}
We don’t have to worry about security because PlayFab encrypts and hashes the password.
The full script should look like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using PlayFab;
using PlayFab.ClientModels;
public class PlayFabCode : MonoBehaviour
{
public InputField Username, Email, Password;
public Text ErrorMessage;
public string SceneName = "";
public void RegisterClick()
{
var register = new RegisterPlayFabUserRequest { Username = Username.text, Email = Email.text, Password = Password.text };
PlayFabClientAPI.RegisterPlayFabUser(register, OnRegisterSuccess, OnRegisterFailure);
}
private void OnRegisterSuccess(RegisterPlayFabUserResult result)
{
ErrorMessage.text = "";
SceneManager.LoadScene(SceneName);
}
private void OnRegisterFailure(PlayFabError error)
{
if (error.ErrorDetails != null && error.ErrorDetails.Count > 0)
{
using (var iter = error.ErrorDetails.Keys.GetEnumerator())
{
iter.MoveNext();
string key = iter.Current;
ErrorMessage.text = error.ErrorDetails[key][0];
}
}
else
{
ErrorMessage.text = error.ErrorMessage;
}
}
public void LoginClick()
{
var login = new LoginWithPlayFabRequest { Username = Username.text, Password = Password.text };
PlayFabClientAPI.LoginWithPlayFab(login, OnLoginSuccess, OnLoginFailure);
}
private void OnLoginSuccess(LoginResult result)
{
ErrorMessage.text = "";
SceneManager.LoadScene(SceneName);
}
private void OnLoginFailure(PlayFabError error)
{
if (error.ErrorDetails != null && error.ErrorDetails.Count > 0)
{
using (var iter = error.ErrorDetails.Keys.GetEnumerator())
{
iter.MoveNext();
string key = iter.Current;
ErrorMessage.text = error.ErrorDetails[key][0];
}
}
else
{
ErrorMessage.text = error.ErrorMessage;
}
}
void Start()
{
ErrorMessage.text = "";
}
void Update()
{
}
}
We’re done editing this script. Let’s close out of Visual Studio and return to the Unity Editor.
Linking Script Events to the UI
The third and last step to making these UI elements functional is to link them to the script we created.
In the Unity editor Hierarchy, we create an empty object in the scene, where we can consolidate our PlayFab UI controls by right-clicking on the root IntroMenu scene, selecting GameObject > Create Empty, and naming the object "PlayFabControls."
Then we drag and drop the PlayFabCode script file onto the PlayFabControls game object to assign the script to it.
We can now drag and drop each UI element, such as UsernameField, on the script’s corresponding property on the right.
We also set Scene Name to "MainScene" so that the scene-switch upon successful registration or login navigates to the gameplay Unity scene.
Finally, we must add the On Click event handlers to the two buttons. So, we select the RegisterButton element and click the plus (+) button to add a click event handler.
Next, we drag and drop the PlayFabControls element onto the event handler box (where it says None) and then set the Function to PlayFabCode > RegisterClick.
We repeat these steps for the LoginButton and select LoginClick for the function so that it activates the login script path.
Run and Test
And we’re done!
We save the project and click the Play button to run our game. If everything is set up correctly, we can register an account the first time and log in each time afterward using the same credentials.
Next Steps
Using Azure PlayFab, we added a fully-functional user authentication feature to our Unity game project with some UI and very little code. Players can create accounts with unique usernames and log in, paving the way for all other PlayFab features such as score reporting on leaderboards.
Join me in the next article, where we’ll begin creating the backend code that this game will connect to for multiplayer gameplay.
To learn more about Azure PlayFab Analytics, and get overviews of features, quickstart guides, and tutorials, check out Azure PlayFab Analytics documentation.