Unity

The Portal Gaming SDK for Unity facilitates the integration of your game with Portal Identity, providing a robust set of features for blockchain functionality and user authentication.

Compatibility and Support Details

Supported Platforms

  • Windows (64-bit).
  • macOS (minimum version 12.5).
  • Android (minimum version 5.1).
  • iOS (minimum version 15.2).

Supported Unity Versions

  • Unity 2021.3 or newer for Windows, macOS, Android, and iOS.
  • Unity 2019.4 or newer for macOS, Android, and iOS.
    • Note: Windows is not supported on Unity versions from 2019.4 up through 2021.2.

Target Platform vs Unity Editor Platform

It's important to understand the relationship between the target platform and the Unity Editor platform:

TARGET PLATFORMWINDOWS UNITY EDITORMACOS UNITY EDITOR
Windows
macOS
Android
iOS

Please note: This table indicates which editor you can use to build for a specific platform target. It does not determine whether you can run the SDK in that editor.

Creating an OAuth2.0 Native Client

Before using the SDK, you need to set up an OAuth2.0 Native client. Follow these steps:

  1. Application Type: Register your application as an OAuth 2.0 Native client.
  2. Client Name: Choose a name to identify your application.
  3. Redirect URLs:
    • For PKCE login on Android, iOS, and macOS: Set your application's deep link (e.g., mygame://callback).
    • Otherwise: Set it to your website or https://localhost:3000.
    • Note: Windows clients do not support PKCE login and do not use Redirect URLs.
  4. Logout URLs:
    • For PKCE login on Android, iOS, and macOS: Set your application's logout deep link (e.g., mygame://logout).
    • The logout deep link must differ from the Redirect URL.
    • Otherwise: Use your website, https://localhost:3000, or set it to be the same as Redirect URLs.
    • Note: Windows clients do not use Logout URLs.
  5. Web Origins URLs: The Unity SDK doesn't utilize this field. You may leave it blank.

Installation

  1. Install git-lfs from https://git-lfs.com/.
  2. Clone the portal-unity repository.
  3. In Unity, open the Package Manager.
  4. Click the add + button and select "Add package from disk...".
  5. Navigate to the Identity package root folder (src/Packages/Identity).
  6. Double-click the package.json file.

Install from a ZIP File

  1. Go to our Unity SDK GitHub Releases.
  2. Download the portal-unity.zip for your desired version
  3. Extract the ZIP file.
  4. In Unity, open the Package Manager.
  5. Click the add + button and select "Add package from disk...".
  6. Navigate to the Identity package root folder (src/Packages/Identity).
  7. Double-click the package.json file.

Install from a Git URL

Via UPM Window

  1. Install git-lfs from https://git-lfs.com/.
  2. In Unity, open the Package Manager.
  3. Click the add + button and select "Add package from git URL...".
  4. Enter https://github.com/portalgaming-com/portal-unity.git?path=/src/Packages/Identity and click 'Add'.

Via manifest.json

  1. Install git-lfs from https://git-lfs.com/.
  2. Open your project's Packages/manifest.json file.
  3. Add "com.portalgaming.identity": "https://github.com/portalgaming-com/portal-unity.git?path=/src/Packages/Identity" in the dependencies block.

Install a Specific Version

To install a specific version, append '#' followed by the version tag to the git URL. For example: https://github.com/portalgaming-com/portal-unity.git?path=/src/Packages/Identity#v1.0.0

Dependencies

The Unity SDK requires the UniTask package (version 2.3.3). Follow the instructions here to install UniTask.

If you encounter conflicts, refer to Unity's guide here.

Quick Start

Initialize Portal Identity

Create a script with the following code and attach it to a GameObject:

using UnityEngine;
using Portal.Identity;

public class InitIdentity : MonoBehaviour
{
    private Identity identity;

    async void Start()
    {
        string clientId = "YOUR_CLIENT_ID";
        identity = await Identity.Init(clientId);
    }
}

After initialization, Identity is accessible from anywhere via Identity.Instance.

Authentication with Portal Identity

To authenticate the user with Identity:

await identity.Authenticate();

This opens the user's default browser for the auth flow.

Stored Credentials

The SDK stores user credentials (access, ID, and refresh tokens) after successful authentication. To re-authenticate using saved credentials:

bool hasCredsSaved = await identity.HasCredentialsSaved();
if (hasCredsSaved)
{
    await identity.Authenticate(useCachedSession: true);
    // Successfully re-authenticated with Identity
}

Note: If re-authentication fails, it will not fall back to the Device Code Authorization flow.

Logout

To perform a full/hard logout:

await identity.Logout(/* hardLogout: true */);

For a local-only logout, set hardLogout to false.

PKCE Login and Logout (Android, iOS, and macOS)

For Android, iOS, and macOS, you can use the PKCE login flow:

  1. Define a deep link scheme (e.g., myapp://callback for login, myapp://logout for logout).
  2. Add these deep links to your client's Redirect URLs and Logout URLs.
  3. Set these in the Identity Init:
    string clientId = "YOUR_CLIENT_ID";
    string redirectUri = "myapp://callback";
    string logoutRedirectUri = "myapp://logout";
    identity = await Identity.Init(clientId, redirectUri, logoutRedirectUri);
    
  4. Use LoginPKCE instead of Login, and LogoutPKCE instead of Logout.

Platform-Specific Setup

Android Setup

  1. In Unity, go to Build Settings -> Player Settings -> Android -> Publishing Settings.
  2. Enable Custom Main Manifest and Custom Main Gradle Template.
  3. Modify Assets/Plugins/Android/AndroidManifest.xml:
    <activity
      android:name="com.portalgaming.unity.RedirectActivity"
      android:exported="true" >
      <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="mygame" android:host="callback" />
        <data android:scheme="mygame" android:host="logout" />
      </intent-filter>
    </activity>
    
  4. Modify Assets/Plugins/Android/mainTemplate.gradle:
    dependencies {
        implementation('androidx.browser:browser:1.5.0')
    }
    

Note: Ensure compileSdkVersion is at least 33.

Proguard Configuration

If using Minify:

  1. Enable Custom Proguard File in Publishing Settings.

  2. Add to Assets/Plugins/Android/proguard-user.txt:

    -dontwarn com.portalgaming.**
    -keep class com.portalgaming.** { *; }
    -keep interface com.portalgaming.** { *; }
    
    -dontwarn androidx.**
    -keep class androidx.** { *; }
    -keep interface androidx.** { *; }
    

iOS Setup

  1. In Unity, go to Build Settings -> Player Settings -> iOS -> Other Settings -> Supported URL schemes.
  2. Increment the Size number.
  3. Add your URL scheme (e.g., mygame for mygame://callback).

macOS Setup

No additional setup required.

Onchain Execution

The ExecuteTransaction method allows you to create and execute blockchain transactions directly from your Unity game. Here's how to use it:

public async void OnMintClicked()
{
    Debug.Log("Mint button clicked");
    string transactionHash = await identity.ExecuteTransaction(new TransactionRequest()
    {
        ChainId = 80002,
        ContractId = "con_f9cd72df-66d8-48c8-bf64-529ae02bdd15",
        PolicyId = "pol_c0638f95-2de5-491e-b9ae-bf4bb2f0917a",
        FunctionName = "mint",
        FunctionArgs = new List<string> { "0x37eC246fCD668400Df5dAA5362601dB613BAcC84" }
    });
    Debug.Log("mintedToken: " + transactionHash);
}

This method takes a TransactionRequest object with the following properties:

  • ChainId: The ID of the blockchain network.
  • ContractId: The ID of the smart contract you're interacting with.
  • PolicyId: The ID of the policy governing the transaction.
  • FunctionName: The name of the function you're calling on the smart contract.
  • FunctionArgs: A list of arguments to pass to the function.

The method returns the transaction hash, which you can use to track the transaction's status on the blockchain.

Requesting a Wallet Session Key

The RequestWalletSessionKey method creates a session key for the logged-in user, which can be used for subsequent wallet operations. Here's how to use it:

public async void OnRequestSessionClicked()
{
    Debug.Log("Request session button clicked");
    await identity.RequestWalletSessionKey();
    Debug.Log("Created session");
}

This method doesn't take any parameters and doesn't return a value. It creates a session key internally, which the SDK will use for future wallet operations.

Supported Functionality


METHODDESCRIPTION
InitializeIdentityInitializes Portal Identity
AuthenticateAuthenticates using Device Code Authorization
AuthenticatePKCEAuthenticates using PKCE (Android, iOS, macOS only)
HasCredentialsSavedChecks for stored credentials
GetAccessTokenRetrieves the user's access token
GetIdTokenRetrieves the user's ID token
LogoutLogs the user out of Identity and removes stored credentials
LogoutPKCELogs out using PKCE flow
ExecuteTransactionCreates a blockchain transaction with provided parameters
RequestWalletSessionKeCreates a session key for the logged-in user