Skip to content

Usage

The client-side project contains the code that interacts with the API. This code works both in normal C# projects and in Unity.

AccountService Singleton

This is a unique helper class specifically made for Unity that makes it easy to talk to the API from your Unity game. Whenever you need to work with user accounts in Unity, the AccountService is your go-to class. This service is automatically setup before any Awake method runs.

Before you start using the code, make sure you've set everything up as shown in our installation guide.

Check out some of the examples below or the example scenes in Unity to see how you can use the AccountService.

Example 1: Creating a New Account

This example demonstrates how to use the AccountService to create a new user account from within a Unity game.

using ByteCobra.Accounts.Unity;
using System.Threading.Tasks;
using UnityEngine;

public class AccountCreationExample : MonoBehaviour
{
    // Call this method to start the account creation process
    public async Task CreateNewAccount(
    string email, 
    string username, 
    string password, 
    bool use2Fa = false)
    {
        string? errorMessage = await AccountService.Api.Account.CreateAccountAsync(email, username, password, use2Fa);
        if(errorMessage == null)
            Debug.Log("Account created");
    }
}

Example 2: Logging In

This example demonstrates how to log into your account using the AccountService. For users with two-factor authentication (2FA) enabled, an additional step is required to complete the login process by providing the 2FA code received, typically via email.


public InputField Username;
public InputField Password;
public InputField TwoFactor;

public async void OnLoginClicked()
{
    LoginResult result = 
        await AccountService.Api.Account.LoginAsync(Username.text, Password.text);

    // This is how you can check if 2FA is used.
    bool uses2FA = result.UsesTwoFactorAuthentication;
    if(uses2FA)
    {
      ShowTwoFactorAuthMenu();  
    }
}

public async void OnSubmitTwoFactorCode())
{
    // Send the 2FA code to the server to finalize the login process
    // and get a secret user session token.
    string token = 
        await AccountService.Api.Account.LoginTwoFactorAsync(uint.Parse(TwoFactor.text));
}

Example 2: Banning a User (Admin Operation)

This example shows how an admin can ban a user using the AccountService in Unity. It requires admin privileges to execute this operation so you need to be logged in as an admin before you attempt this.

using ByteCobra.Accounts.Unity;
using System;
using System.Threading.Tasks;
using UnityEngine;

public class BanUserExample : MonoBehaviour
{
    // Call this method to ban a user
    public async Task BanUser(string userId, DateTime bannedUntil)
    {
        await AccountService.Api.Admin.SetBannedUntilAsync(userId, bannedUntil);
        Debug.Log("User banned successfully.");
    }
}