Username / Password - Code
Simple authentication with username and password [IDEN-Username-03]
Using the username and password feature is easy. There are just a few APIs you need to know about to be ready to go. Read more here to learn how to use AddEmail
and RecoverAccountWithEmail
methods of the PlayerAccounts
SDK.
A Beamable Prefab is available for this feature
There is a no-code prefab for this feature. You can find more information about our ship-ready prefabs here.
Declarations
The following code samples assume that you have already initialized the SDK.
private BeamContext _beamContext;
private async void Start()
{
_beamContext = BeamContext.Default;
await _beamContext.OnReady;
await _beamContext.Accounts.OnReady;
}
Add Email
The Beamable SDK always has an implicit account after the BeamContext
has been created. Various credentials may be added to the account, such as an email and password.
public async Promise AddEmail(string email, string password)
{
var result = await _beamContext.Accounts.AddEmail(email, password);
if (!result.isSuccess)
{
Debug.LogError($"Failed to add email, reason=[{result.error}]");
}
}
Error Handling
Be sure to properly handle errors that may come from
AddEmail
. For example, such errors can occur if the email address is not unique.
Login User
If an email and password have been added to an existing account, that account can be recovered by supplying the original credentials. In this code snippet, the RecoverAccountWithEmail
function returns a operation handle that shows the recovered account before setting the current BeamContext
to that account. The operation.account
can be used to show the user information about the account before calling the SwitchToAccount
function, which will change the BeamContext
's current account.
public async Promise Login(string email, string password)
{
var operation = await _beamContext.Accounts.RecoverAccountWithEmail(email, password);
if (operation.isSuccess)
{
Debug.Log($"Found existing account, playerId=[{operation.account.GamerTag}]");
operation.SwitchToAccount();
}
else
{
Debug.LogError($"Failed to recovery account via email, reason=[{operation.error}]");
}
}
Error Handling
If login fails, you will get an error which you must handle appropriately. This can happen if the username and/or password are incorrect. More than likely, you would want to surface this error to the player via the UI.
Updated about 1 year ago