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 PLATFORM | WINDOWS UNITY EDITOR | MACOS 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:
- Application Type: Register your application as an OAuth 2.0 Native client.
- Client Name: Choose a name to identify your application.
- 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.
- For PKCE login on Android, iOS, and macOS: Set your application's deep link (e.g.,
- 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.
- For PKCE login on Android, iOS, and macOS: Set your application's logout deep link (e.g.,
- Web Origins URLs: The Unity SDK doesn't utilize this field. You may leave it blank.
Installation
- Install git-lfs from https://git-lfs.com/.
- Clone the portal-unity repository.
- In Unity, open the Package Manager.
- Click the add + button and select "Add package from disk...".
- Navigate to the Identity package root folder (
src/Packages/Identity
). - Double-click the
package.json
file.
Install from a ZIP File
- Go to our Unity SDK GitHub Releases.
- Download the
portal-unity.zip
for your desired version - Extract the ZIP file.
- In Unity, open the Package Manager.
- Click the add + button and select "Add package from disk...".
- Navigate to the Identity package root folder (
src/Packages/Identity
). - Double-click the
package.json
file.
Install from a Git URL
Via UPM Window
- Install git-lfs from https://git-lfs.com/.
- In Unity, open the Package Manager.
- Click the add + button and select "Add package from git URL...".
- Enter
https://github.com/portalgaming-com/portal-unity.git?path=/src/Packages/Identity
and click 'Add'.
Via manifest.json
- Install git-lfs from https://git-lfs.com/.
- Open your project's Packages/manifest.json file.
- 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:
- Define a deep link scheme (e.g.,
myapp://callback
for login,myapp://logout
for logout). - Add these deep links to your client's Redirect URLs and Logout URLs.
- 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);
- Use
LoginPKCE
instead ofLogin
, andLogoutPKCE
instead ofLogout
.
Platform-Specific Setup
Android Setup
- In Unity, go to Build Settings -> Player Settings -> Android -> Publishing Settings.
- Enable Custom Main Manifest and Custom Main Gradle Template.
- 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>
- 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:
-
Enable Custom Proguard File in Publishing Settings.
-
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
- In Unity, go to Build Settings -> Player Settings -> iOS -> Other Settings -> Supported URL schemes.
- Increment the Size number.
- Add your URL scheme (e.g.,
mygame
formygame://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
METHOD | DESCRIPTION |
---|---|
InitializeIdentity | Initializes Portal Identity |
Authenticate | Authenticates using Device Code Authorization |
AuthenticatePKCE | Authenticates using PKCE (Android, iOS, macOS only) |
HasCredentialsSaved | Checks for stored credentials |
GetAccessToken | Retrieves the user's access token |
GetIdToken | Retrieves the user's ID token |
Logout | Logs the user out of Identity and removes stored credentials |
LogoutPKCE | Logs out using PKCE flow |
ExecuteTransaction | Creates a blockchain transaction with provided parameters |
RequestWalletSessionKe | Creates a session key for the logged-in user |
Updated 28 days ago