Click here to Skip to main content
15,881,173 members
Articles / Game Development / Unity
Article

Unity on Azure PlayFab Part 2: User Registration and Login

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
15 Feb 2022CPOL6 min read 5.9K   1  
In this article we introduce Azure PlayFab from the perspective of a Unity developer.

This article is a sponsored article. Articles such as these are intended to provide you with information on products and services that we consider useful and of value to developers

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.

Image 1

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.

Image 2

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.

Image 3

Image 4

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.

Image 5

Then, we expand each input field and select Placeholder to edit the placeholder text of each to match the field.

Image 6

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.

Image 7

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."

Image 8

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

Image 9

We expand the button elements and update the text for each so that the user knows which button to press.

Image 10

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."

Image 11

We position it below the buttons with Pos Y at 60 and update the text to "Error Message" for clarity.

Image 12

Let’s center the text using the Paragraph > Alignment buttons and change the text to a red color for better visibility.

Image 13

Also, let’s set the Vertical Overflow property to Overflow so that long error messages will also appear before the buttons.

Image 14

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.

Image 15

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.

Image 16

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."

Image 17

Image 18

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:

C#
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:

C#
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:

C#
void Start()
{
ErrorText.text = "";
}

Now we can add some methods to call PlayFab’s account registration API with this code:

C#
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); // Load Main Scene
}

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.

C#
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); // Load Main Scene
}

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:

C#
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); // Load Main Scene
}

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); // Load Main Scene
}

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;
    		}
}

// Start is called before the first frame update
void Start()
{
  	  	ErrorMessage.text = "";
}

// Update is called once per frame
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."

Image 19

Then we drag and drop the PlayFabCode script file onto the PlayFabControls game object to assign the script to it.

Image 20

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.

Image 21

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.

Image 22

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.

Image 23

We repeat these steps for the LoginButton and select LoginClick for the function so that it activates the login script path.

Image 24

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.

Image 25

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.

This article is part of the series 'Unity On Azure PlayFab View All

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Raphael Mun is a tech entrepreneur and educator who has been developing software professionally for over 20 years. He currently runs Lemmino, Inc and teaches and entertains through his Instafluff livestreams on Twitch building open source projects with his community.

Comments and Discussions

 
-- There are no messages in this forum --