Skip to main content

Unity SDK

The Causal Foundry Kenkai SDK for Unity is a Unity Package Manager (UPM) wrapper around the Kenkai Core SDKs for Android and iOS. Game code uses the CausalFoundry.Unity namespace and the CFSDK facade on both platforms.

TargetRequirement
Unity2021.3 LTS or newer
AndroidMinimum SDK 21 and compile SDK 33 or newer
iOSiOS 13.0 or newer and Xcode 13.3 or newer

Mobile testing required

The Unity Editor uses a safe no-op bridge. Use an Android or iOS player build to verify event delivery and real action payloads.


SDK setup and calls

SectionDescription
UPM setupInstall and configure the package.
InitializeAndIdentifyInitialize the SDK, identify a user, and optionally log user-catalog values.
TrackLog a custom event.
LogOtherCatalogLog reusable dimensions for a custom catalog.
FetchActionsFetch actions using explicit action parameters.


Add the SDK with Unity Package Manager

Open the Unity SDK GitHub repository and choose the release or tag you want to install.

In Unity, open Window > Package Manager, click +, choose Add package from git URL, and enter the URL below after replacing <RELEASE_TAG> with the selected version tag:

https://github.com/causalfoundry/unity-sdk.git#<RELEASE_TAG>

Alternatively, add the package to the dependencies object in Packages/manifest.json:

{
"dependencies": {
"io.kenkai.upm.sdk": "https://github.com/causalfoundry/unity-sdk.git#<RELEASE_TAG>"
}
}

Pin production projects to a release tag or full commit SHA. The repository root is the UPM package, so the Git URL does not need a ?path= query.


Configure the SDK

Run Tools > Causal Foundry > Create or Select SDK Settings. In the selected settings asset:

  1. Enter the raw SDK key from the Kenkai Platform.
  2. Keep Auto Initialize enabled for the normal integration.

Reference the SDK from a custom assembly

Unity does not automatically modify a consumer project's custom Assembly Definitions. If the game uses a custom Assembly Definition:

  1. Select the consuming .asmdef asset in Unity's Project window.
  2. Under Assembly Definition References, click +.
  3. Select CausalFoundry.Unity.
  4. Click Apply.

The resulting .asmdef references should include:

"references": [
"CausalFoundry.Unity"
]

Consumer scripts normally need these imports:

using System.Collections.Generic;
using CausalFoundry.Unity;

Add using UnityEngine; when using Debug in the examples below.



InitializeAndIdentify

InitializeAndIdentify helps identifies the user, it should provide the ID of the user as in your system and optionally logs string-valued user-catalog dimensions.

Overview

ParamUsabilityFormatEnum ValuesDescription
userIdREQUIREDSTRING---A stable, unique ID from the game's account system. Do not use one shared literal ID for every user.
identityActionREQUIREDIdentityActionRegister, Login, LogoutThe identity transition to record. Use Register when introducing a new identity, Login for later authenticated sessions, and Logout when ending the authenticated session.
userCatalogOPTIONALIDictionary<string, string>---String-valued user dimensions. Pass null or an empty dictionary to skip catalog logging. Defaults to null.
completionOPTIONALAction<CFResult>---Called on Unity's main thread with the first failure, or with success after every requested operation is accepted. Defaults to null.

Usage

using System.Collections.Generic;
using CausalFoundry.Unity;
using UnityEngine;

string userId = "YOUR_STABLE_USER_ID";
IdentityAction identityAction = IdentityAction.Login;

IDictionary<string, string> userCatalog =
new Dictionary<string, string> // example properties
{
{ "account_type", "game_user" },
{ "region", "europe" }
};

CFSDK.InitializeAndIdentify(
userId,
identityAction,
userCatalog,
result =>
{
if (!result.IsSuccess)
{
Debug.LogError("InitializeAndIdentify failed: " + result.Error);
return;
}

Debug.Log("SDK initialized and user identified.");
});

Pass null when no user-catalog values are needed:

CFSDK.InitializeAndIdentify(
userId,
IdentityAction.Login,
null,
result =>
{
if (!result.IsSuccess)
Debug.LogError(result.Error);
});

Call this function from Unity's main thread. If Auto Initialize already started with matching settings, the function joins that initialization instead of creating a second SDK instance.

A successful result means the native SDK accepted or dispatched the requested operations; it is not a server-delivery acknowledgement. The operations are not rolled back. If catalog logging fails after identification succeeds, retry LogUserCatalog directly rather than rerunning the entire helper.

Every Identify event automatically includes meta.unity_version with the installed UPM package version.

Actions work after initialization

After InitializeAndIdentify completes successfully, SDK actions work out of the box. No additional action setup is required unless the game will manually fetch and render predefined actions. Notification-based actions also require the user permission described below.

Notification permission is required for notification actions

Your app must ask each user for notification permission. If permission is not granted, the UPM SDK cannot display notification-based actions. Explain why notifications are useful, then request permission after initialization succeeds.

This applies to Android and iOS. Notification permission is not required for custom actions or in-app messages.



Track

Call Track after a successful identity callback when the event must be associated with that user.

Overview

ParamUsabilityFormatEnum ValuesDescription
eventNameREQUIREDSTRING---The custom event name. It is trimmed, lowercased, and has spaces replaced with underscores. Built-in SDK event names are rejected.
optionsOPTIONALTrackOptions---The event's optional primary property, metadata, upload preference, and timestamp. Defaults to an empty TrackOptions.
completionOPTIONALAction<CFResult>---Called after the native SDK accepts or dispatches the event, or with an error. Defaults to null.

TrackOptions values

ValueUsabilityFormatDescription
PropertyOPTIONALSTRINGA single primary value associated with the event.
MetadataOPTIONALIDictionary<string, object>Additional JSON-compatible values associated with the event.
UpdateImmediatelyOPTIONALbool?Overrides the SDK-level upload preference for this event where supported.
TimestampMillisecondsOPTIONALlong?Unix timestamp in milliseconds. Native SDKs that do not support it ignore the value.

Usage

CFSDK.Track(
"level_completed",
new TrackOptions
{
Property = "level_7",
Metadata = new Dictionary<string, object>
{
{ "score", 1200 },
{ "perfect", true },
{ "attempts", 2 }
}
},
result =>
{
if (!result.IsSuccess)
Debug.LogError("Track failed: " + result.Error);
});

Metadata can contain strings, booleans, finite numbers, lists, string-keyed dictionaries, and null values. A successful callback means the native SDK accepted or dispatched the event; it is not a server-delivery acknowledgement.

Every custom Track event automatically includes meta.unity_version with the installed UPM package version. If caller metadata contains the same key, the SDK-owned value is used in the outbound copy without modifying the caller's dictionary.



LogOtherCatalog

Use LogOtherCatalog to attach reusable dimensions to a custom catalog subject. This logs catalog data; use Track for custom events.

Overview

ParamUsabilityFormatEnum ValuesDescription
subjectIdREQUIREDSTRING---The non-empty identifier for the catalog subject.
catalogNameREQUIREDSTRING---The custom catalog name. Names reserved by the SDK's built-in catalogs are rejected.
metadataREQUIREDIDictionary<string, object>---At least one JSON-compatible string-keyed catalog value.
completionOPTIONALAction<CFResult>---Called after the catalog is accepted or dispatched, or with an error. Defaults to null.

Usage

string subjectId = "household_123";
string catalogName = "household";

IDictionary<string, object> metadata =
new Dictionary<string, object>
{
{ "head_household_id", "user_456" },
{ "members", 4 },
{ "is_approved", true }
};

CFSDK.LogOtherCatalog(
subjectId,
catalogName,
metadata,
result =>
{
if (!result.IsSuccess)
Debug.LogError("Other Catalog failed: " + result.Error);
});

subjectId and catalogName must be non-empty, and metadata must contain at least one value. For validation, surrounding whitespace is removed from the catalog name, internal whitespace is replaced with underscores, and the name is lowercased. Reserved built-in catalog names are rejected.



FetchActions

Use FetchActions when the game owns custom-action rendering. Before the SDK initializes:

  1. Run Tools > Causal Foundry > Create or Select SDK Settings.
  2. In the settings Inspector, disable Auto Show In App Messages.
  3. Save the settings asset.
  4. Restart Play mode, or rebuild and relaunch the mobile player, so the setting is applied during initialization.

Call FetchActions only after initialization succeeds.

Overview

ParamUsabilityFormatEnum ValuesDescription
invActionTypeREQUIREDSTRING CONSTANTActionTypes.Message, ActionTypes.Custom, ActionTypes.UiComponentThe category of action to fetch.
actionRenderMethodTypeREQUIREDSTRING CONSTANTActionRenderMethods.PushNotification, ActionRenderMethods.InAppMessage, ActionRenderMethods.InAppComponentThe action's render method.
deliveryModeREQUIREDSTRING CONSTANTActionDeliveryModes.OneOff, ActionDeliveryModes.CachedWhether to return the action once or use matching cached actions until expiry.
actionAttributesREQUIRED (NULLABLE)IDictionary<string, string>null, empty dictionary, populated dictionarySupply this argument for optional string filters. null and an empty dictionary both fetch without attribute filters.
completionREQUIREDAction<CFResult<IList<CFAction>>>---Called on Unity's main thread with the fetched actions or an error. Returned actions are not rendered automatically.

Fetch action parameter values

ParameterUnity valueUnity wire valueDescription
invActionTypeActionTypes.MessagemessageMessage actions such as notifications or in-app messages.
invActionTypeActionTypes.CustomcustomRecommended cross-platform value for custom UI actions. On iOS, it maps to the native UI-component action type.
invActionTypeActionTypes.UiComponentui-componentiOS-oriented alias for UI-component actions. Prefer Custom for cross-platform calls.
actionRenderMethodTypeActionRenderMethods.PushNotificationpush_notificationSelect notification-rendered actions.
actionRenderMethodTypeActionRenderMethods.InAppMessagein_app_messageSelect native in-app-message actions. The fetched result is still returned to the callback.
actionRenderMethodTypeActionRenderMethods.InAppComponentin_app_componentReturn content for the game's custom Unity UI.
deliveryModeActionDeliveryModes.OneOffone-offReturn an action once.
deliveryModeActionDeliveryModes.CachedcachedReturn matching cached actions until they expire.
actionAttributesnull{}Fetch without attribute filters.
actionAttributesnew Dictionary<string, string>(){}Also fetch without attribute filters.
actionAttributesPopulated Dictionary<string, string>String mapFilter using attributes configured for the action.

Usage

CFSDK.FetchActions(
invActionType: ActionTypes.Custom,
actionRenderMethodType: ActionRenderMethods.InAppComponent,
deliveryMode: ActionDeliveryModes.OneOff,
actionAttributes: new Dictionary<string, string>
{
{ "hello", "world" }
},
completion: result =>
{
if (!result.IsSuccess)
{
Debug.LogError("FetchActions failed: " + result.Error);
return;
}

foreach (CFAction action in result.Value)
{
string title = action.Payload?.Content?.Title;
string body = action.Payload?.Content?.Body;

// Render the returned content with the game's Unity UI.
Debug.Log(title + ": " + body);
}
});

Every attribute key and value must be a string. Pass null or an empty Dictionary<string, string> when no filters are needed; attributes are a key/value map, not a C# List.

Returned actions are never displayed automatically. In the Unity Editor, valid fetches return an empty list. Use an Android or iOS player build to verify real action payloads.



For deeper platform build details and troubleshooting, see the Unity SDK installation guide and native integration notes.