Skip to content

Unity Application Integration


Prerequisites

Note: If you have enabled the RUM Headless service, the prerequisites are automatically configured for you. You can proceed directly to integrate the application.

Application Integration

  1. Go to RUM > Create Application > Android/iOS;
  2. Create two separate applications for Unity Android and Unity iOS to receive RUM data from the Android and iOS platforms respectively;
  3. Enter the corresponding Application Name and Application ID for each platform's application;
  4. Choose the application integration method:
    • Public DataWay: Directly receives RUM data without installing the DataKit collector.
    • Local Environment Deployment: Receives RUM data after meeting the prerequisites.

Installation

Source Code Repository: https://github.com/GuanceCloud/datakit-unity

Demo Repository: https://github.com/GuanceCloud/datakit-unity/blob/dev/Assets/Scenes

Assets/Plugins
├── Android
│   ├── FTUnityBridge.java                  // Android bridge
│   ├── InnerClassProxy.java                // Android Inner Setting Proxy
│   ├── ft-sdk-release.aar                  // Android SDK
│   ├── gson-2.8.5.jar                      // Android SDK third-party dependency
├── iOS
│   ├── FTMobileSDK.xcframework             // iOS SDK
│   ├── FTUnityBridge.mm                    // iOS bridge
├── FTSDK.cs                                // FTSDK.prefab bound script
├── FTSDK.prefab                            // SDK initialization prefab
├── FTUnityBridge.cs                        // Unity bridge connecting iOS, Android, and other platform methods
├── FTViewObserver.cs                       // FTViewObserver.prefab bound script
├── FTViewObserver.prefab                   // View page monitoring prefab
├── UnityMainThreadDispatcher.cs            // UnityMainThreadDispatcher.prefab bound script
├── UnityMainThreadDispatcher.prefab        // Main thread consumption queue prefab
  • Asserts -> Import Package -> Custom Package... to import ft-sdk-unity.unitypackage
  • Add the JSON parsing third-party library "com.unity.nuget.newtonsoft-json", which can be added via Pakcage Manager -> Add Package by name ...
  • Drag the FTSDK.prefab into the first scene page, and initialize the SDK in the _InitSDK method within FTSDK.cs. If the native Android and iOS projects have already integrated the native SDK, comment out the _InitSDK method to avoid duplicate settings.
  • Drag the FTViewObserver.prefab into other scene pages to achieve View lifecycle monitoring, including application sleep and wake.
  • Monitor and convert Unity crash data and regular log data via Application.logMessageReceived, refer to the OnEnable and OnDisable methods in FTSDK.cs.
  • iOS Plugin Inspector Settings: Since FTMobileSDK.xcframework is a dynamic library, click on FTMobileSDK.xcframework and check Add to Embedded Binaries. Selecting this option will make Unity set the Xcode project options to copy the plugin files into the final application bundle. unity_ios_plugin_embedded

Note: If the native SDK (Android gson-2.8.5.jar, ft-sdk-release.aar; iOS FTMobileSDK.framework) is already integrated, you can remove them from the project. Additionally, Android Okhttp requests and startup time consumption features require the use of ft-plugin. For detailed configuration, please refer to Android SDK

Initialization

FTUnityBridge.Install(new SDKConfig
            {
                datakitUrl = "http://10.0.0.1:9529",
                env = "prod",
                debug = true,

            });
Field Type Required Description
datakitUrl string Yes URL address for local environment deployment (Datakit) reporting, e.g., http://10.0.0.1:9529, default port 9529. The device installing the SDK must be able to access this address. Note: Choose one between datakitUrl and datawayUrl configuration
datawayUrl string Yes Public Dataway reporting URL address, obtained from the [RUM] application, e.g., https://open.dataway.url. The device installing the SDK must be able to access this address. Note: Choose one between datakitUrl and datawayUrl configuration
clientToken string Yes Authentication token, must be used together with datawayUrl
debug boolean No Sets whether to allow printing Debug logs, default false
env string No Environment, default prod, any character, recommended to use a single word, e.g., test, etc.
serviceName string No Sets the name of the associated business or service, default: df_rum_ios, df_rum_android
globalContext object No Adds custom tags
autoSync boolean No Whether to automatically sync collected data to the server. Default YES. When NO, use the flushSyncData method to manage data synchronization manually
syncPageSize number No Sets the number of entries per sync request. Range [5,). Note: A larger number of request entries means data synchronization consumes more computing resources, default is 10
syncSleepTime number No Sets the sync interval time. Range [0,5000], default is not set
enableDataIntegerCompatible boolean No Recommended to enable when coexistence with web data is needed. This configuration handles web data type storage compatibility issues. Enabled by default in SDK versions 1.1.0 and above
compressIntakeRequests boolean No Compresses uploaded sync data using deflate, disabled by default, supported in SDK versions 1.1.0 and above
enableLimitWithDbSize boolean No Enables using DB to limit data size, default 100MB, unit Byte. A larger database increases disk pressure, disabled by default.
Note: When enabled, the Log configuration logCacheLimitCount and RUM configuration rumCacheLimitCount become invalid. Supported in SDK versions 1.1.0 and above
dbCacheLimit number No DB cache size limit. Range [30MB,), default 100MB, unit byte, supported in SDK versions 1.1.0 and above
dbDiscardStrategy string No Sets the data discard rule in the database.
Discard strategy: discard discard new data (default), discardOldest discard old data. Supported in SDK versions 1.1.0 and above
dataModifier object No Modifies a single field. Supported in SDK 1.1.0 and above, see usage example here
lineDataModifier object No Modifies a single piece of data. Supported in SDK 1.1.0 and above, see usage example here

RUM Configuration

FTUnityBridge.InitRUMConfig(new RUMConfig()
            {
                androidAppId = "androidAppId",
                iOSAppId = "iOSAppId",
                sampleRate = 0.8f,
            });
Field Type Required Description
androidAppId string Yes Corresponds to setting the RUM appid, which enables RUM collection functionality. Method to obtain appid
iOSAppId string Yes Corresponds to setting the RUM appid, which enables RUM collection functionality. Method to obtain appid
sampleRate float No Sampling rate, value range [0,1], 0 means no collection, 1 means full collection, default value is 1. Scope: all View, Action, LongTask, Error data under the same session_id
sessionOnErrorSampleRate float No Sets the error collection rate. When a session is not sampled by sampleRate, if an error occurs during the session, data from the 1 minute before the error can be collected. Value range [0,1], 0 means no collection, 1 means full collection, default value is 0. Scope: all View, Action, LongTask, Error data under the same session_id
enableNativeUserAction boolean No Whether to track Native Action, Button click events. Recommended to disable for pure uni-app applications, default is false, not supported for Android cloud builds.
enableNativeUserResource boolean No Whether to enable automatic Native Resource tracking, default is false, not supported for Android cloud builds. Since uniapp network requests on iOS are implemented using system APIs, enabling this will collect all iOS resource data. Please disable manual collection on iOS at this time to prevent duplicate data collection.
enableNativeUserView boolean No Whether to enable automatic Native View tracking. Recommended to disable for pure uni-app applications, default is false.
errorMonitorType string/array No Error monitoring supplement types: all, battery, memory, cpu, default is not set.
deviceMonitorType string/array No Page monitoring supplement types: all, battery (Android only), memory, cpu, fps, default is not set.
detectFrequency string No Page monitoring frequency: normal (default), frequent, rare.
globalContext object No Custom global parameters, special key: track_id (used for tracking functionality).
enableResourceHostIP boolean No Whether to collect the IP address of the requested target domain. Scope: only affects the default collection when enableNativeUserResource is true. iOS: supported on >= iOS 13. Android: A single Okhttp has an IP caching mechanism for the same domain. For the same OkhttpClient, if the server IP does not change, it will only be generated once.
enableTrackNativeCrash boolean No Whether to enable monitoring of Android Java Crash and OC/C/C++ crashes, default is false.
enableTrackNativeAppANR boolean No Whether to enable Native ANR monitoring, default is false.
enableTrackNativeFreeze boolean No Whether to enable automatic Native Freeze tracking, default is false.
nativeFreezeDurationMs number No Sets the threshold for collecting Native Freeze stutters. Value range [100,), unit milliseconds. iOS default 250ms, Android default 1000ms.
rumDiscardStrategy string No Discard strategy: discard discard new data (default), discardOldest discard old data.
rumCacheLimitCount number No Local cache maximum RUM entry count limit [10_000,), default 100_000.

Log Configuration

FTUnityBridge.InitLogConfig(new LogConfig
            {
                sampleRate = 0.9f,
                enableCustomLog = true,
                enableLinkRumData = true,
            });
Field Type Required Description
sampleRate float No Sampling rate, value range [0,1], 0 means no collection, 1 means full collection, default value is 1.
enableLinkRumData boolean No Whether to associate with RUM data.
enableCustomLog boolean No Whether to enable custom logs.
discardStrategy string No Log discard strategy: discard discard new data (default), discardOldest discard old data.
logLevelFilters array No Log level filtering, the array must contain log levels: info, warning, error, critical, ok (recovery).
globalContext object No Custom global parameters.
logCacheLimitCount number No Local cache maximum log entry count limit [1000,). Larger logs mean greater disk cache pressure, default 5000.

Trace Configuration

FTUnityBridge.InitTraceConfig(new TraceConfig
            {
                sampleRate = 0.9f,
                traceType = TraceType.DDTrace,
                enableNativeAutoTrace = true,
                enableLinkRumData = true

            });
Field Type Required Description
sampleRate float No Sampling rate, value range [0,1], 0 means no collection, 1 means full collection, default value is 1.
traceType string No Trace type: ddTrace (default), zipkinMultiHeader, zipkinSingleHeader, traceparent, skywalking, jaeger.
enableLinkRUMData boolean No Whether to associate with RUM data, default false.
enableNativeAutoTrace boolean No Whether to enable native network auto-tracing for iOS NSURLSession, Android OKhttp, default false, not supported for Android cloud builds. Since uniapp network requests on iOS are implemented using system APIs, enabling this will automatically trace network requests initiated by uniapp on iOS. Please disable manual trace linking on iOS at this time to prevent incorrect association between traces and RUM data.

RUM User Data Tracking

Currently, RUM data transmission can only be achieved by manually calling methods.

Action

Usage

/// <summary>
///  Add Action
/// </summary>
/// <param name="actionName"> action name</param>
/// <param name="actionType"> action type</param>
public static void StartAction(string actionName, string actionType)

/// <summary>
/// Add Action
/// </summary>
/// <param name="actionName">action name</param>
/// <param name="actionType">action type</param>
/// <param name="property">Additional property parameters</param>
public static void StartAction(string actionName, string actionType, Dictionary<string, object> property)

/// <summary>
/// Add Action
/// </summary>
/// <param name="actionName">action name</param>
/// <param name="actionType">action type</param>
public static void AddAction(string actionName, string actionType)



/// <summary>
/// Add Action
/// </summary>
/// <param name="actionName">action name</param>
/// <param name="actionType">action type</param>
/// <param name="property">Additional property parameters</param>
public static void AddAction(string actionName, string actionType, Dictionary<string, object> property)

Code Example

 FTUnityBridge.StartAction("click", "test");

View

Usage

/// <summary>
///  View Start
/// </summary>
/// <param name="viewName">Current page name</param>
public static void StartView(string viewName)

/// <summary>
/// View Start
/// </summary>
/// <param name="viewName">Current page name</param>
/// <param name="property">Additional property parameters</param>
public static void StartView(string viewName, Dictionary<string, object> property)

/// <summary>
/// View End
/// </summary>
public static void StopView()

/// <summary>
/// View End
/// </summary>
/// <param name="property">Additional property parameters</param>
public static void StopView(Dictionary<string, object> property)

Code Example

FTUnityBridge.StartView("TEST_VIEW_ONE");

FTUnityBridge.StopView();

Resource

Usage

/// <summary>
///  resource start
/// </summary>
/// <param name="resourceId">Resource Id</param>
/// <returns></returns>
public static async Task StartResource(string resourceId)

/// <summary>
/// resource start
/// </summary>
/// <param name="resourceId">Resource Id</param>
/// <param name="property">Additional property parameters</param>
/// <returns></returns>
public static async Task StartResource(string resourceId, Dictionary<string, object> property)

/// <summary>
/// resource end
/// </summary>
/// <param name="resourceId">Resource Id</param>
/// <returns></returns>
public static async Task StopResource(string resourceId)

/// <summary>
/// resource end
/// </summary>
/// <param name="resourceId">Resource Id</param>
/// <param name="property">Additional property parameters</param>
public static async Task StopResource(string resourceId, Dictionary<string, object> property)


/// <summary>
/// Add network transmission content and metrics
/// </summary>
/// <param name="resourceId">Resource Id</param>
/// <param name="resourceParams">Data transmission content</param>
/// <param name="netStatus">Network metric data</param>
public static async Task AddResource(string resourceId, ResourceParams resourceParams)
ResourceParams
Method Name Type Required Description
url string Yes url address
requestHeader string No Request header parameters, no format restrictions.
responseHeader string No Response header parameters, no format restrictions.
responseConnection string No Response connection.
responseContentType string No Response ContentType.
responseContentEncoding string No Response ContentEncoding.
resourceMethod string No Request method GET, POST, etc.
responseBody string No Return body content.

Code Example

FTUnityBridge.StartResource(resourceId);

FTUnityBridge.StopResource(resourceId);

ResourceParams resourceParams = new ResourceParams();
resourceParams.url = url;
resourceParams.requestHeader = client.DefaultRequestHeaders.ToDictionary(header => header.Key, header => string.Join(",", header.Value));
resourceParams.responseHeader = response.Headers.ToDictionary(header => header.Key, header => string.Join(",", header.Value));
resourceParams.resourceStatus = (int)response.StatusCode;
resourceParams.responseBody = responseData;
resourceParams.resourceMethod = "GET";

FTUnityBridge.AddResource(resourceId, resourceParams);

Error

Usage

/// <summary>
/// Add error information
/// </summary>
/// <param name="log">Log</param>
/// <param name="message">Message</param>
/// <param name="errorType">Error type</param>
/// <param name="state">Program running state</param>
/// <returns></returns>
public static async Task AddError(string log, string message)


/// <summary>
/// Add error information
/// </summary>
/// <param name="log">Log</param>
/// <param name="message">Message</param>
/// <param name="errorType">Error type</param>
/// <param name="state">Program running state</param>
/// <param name="property">Additional property parameters</param>
/// <returns></returns>
public static async Task AddError(string log, string message,
    Dictionary<string, object> property)

Code Example

void OnEnable()
{
    Application.logMessageReceived += LogCallBack;

}

void OnDisable()
{
    Application.logMessageReceived -= LogCallBack;
}

void LogCallBack(string condition, string stackTrace, LogType type)
{
    if (type == LogType.Exception)
    {
        FTUnityBridge.AddError(stackTrace, condition);
    }

}

LongTask

Usage

/// <summary>
/// Add long-running task
/// </summary>
/// <param name="log">Log content</param>
/// <param name="duration">Duration, nanoseconds</param>
/// <returns></returns>
public static async Task AddLongTask(string log, long duration)

/// <summary>
/// Add long-running task
/// </summary>
/// <param name="log">Log content</param>
/// <param name="duration">Duration, nanoseconds</param>
/// <param name="property">Additional property parameters</param>
/// <returns></returns>
public static async Task AddLongTask(string log, long duration, Dictionary<string, object> property)

Code Example

FTUnityBridge.AddLongTask("long task test", 100002);

Log Printing

Currently, log content is limited to 30 KB. Characters beyond this limit will be truncated.

Usage

/// <summary>
/// Add log
/// </summary>
/// <param name="log">Log content</param>
/// <param name="level">Log level info, warning, error, critical, ok</param>
/// <returns></returns>
public static async Task AddLog(string log, LogLevel level)

 /// <summary>
/// Add log
/// </summary>
/// <param name="log">Log content</param>
/// <param name="level">Log level info, warning, error, critical, ok</param>
/// <param name="property">Additional property parameters</param>
/// <returns></returns>
public static async Task AddLog(string log, LogLevel level, Dictionary<string, object> property)

LogLevel

Method Name Meaning
info Info
warning Warning
error Error
critical Critical
ok Ok (Recovery)

Code Example

FTUnityBridge.AddLog("test log", "test message");

Tracer Network Trace Linking

Trace linking is achieved by generating Trace Headers and adding them to the http request headers.

Usage

/// <summary>
/// Get trace Id
/// </summary>
/// <param name="url">url address</param>
/// <returns>json string</returns>
public static async Task<string> GetTraceHeaderWithUrl(string url)


/// <summary>
/// Get trace
/// </summary>
/// <param name="resourceId">Resource Id</param>
/// <param name="url">url address</param>
/// <returns>json string</returns>
public static async Task<string> GetTraceHeader(string resourceId, string url)

Code Example

string headData = FTUnityBridge.GetTraceHeader(resourceId, FAKE_URL);

string headData = FTUnityBridge.GetTraceHeader(FAKE_URL);

Clear SDK Cache Data

Use FTUnityBridge to clear cached data that has not been uploaded.

/**
 * Clears all data that has not yet been uploaded to the server.
*/
FTUnityBridge.clearAllData();

Active Data Synchronization

When SDKConfig.autoSync is configured as true, no additional action is needed; the SDK will perform automatic synchronization.

When SDKConfig.autoSync is configured as false, you need to actively trigger the data synchronization method to sync data.

/**
 * Actively synchronizes data. When `FTMobileConfig.autoSync=false` is configured, this method needs to be actively triggered to perform data synchronization.
 * @returns a Promise.
 */
FTUnityBridge.flushSyncData();

Add Custom Tags

/// <summary>
/// Add custom global parameters. Affects RUM and Log data.
/// </summary>
public static void AppendGlobalContext(Dictionary<string, object> property)

/// <summary>
/// Add custom RUM global parameters. Affects RUM data.
/// </summary>
public static void AppendRUMGlobalContext(Dictionary<string, object> property)

/// <summary>
/// Add custom RUM and Log global parameters. Affects Log data.
/// </summary>
public static void AppendLogGlobalContext(Dictionary<string, object> property)

User Information Binding and Unbinding

Usage

/// <summary>
/// Bind RUM user information
/// </summary>
/// <param name="userId">User unique id</param>
public static async Task BindUserData(string userId)

/// <summary>
/// Bind RUM user information
/// </summary>
/// <param name="userData"></param>
public static async Task BindUserData(UserData userData)
Method Name Type Required Description
userId string Yes User id
userName string No Username
userEmail string No User email
extra dictionary No Assign values in KV format. Please check the rules for adding here.

Code Example

FTUnityBridge.BindUserData(new UserData
            {
                userId = "userid",
                userName = "userName",
                userEmail = "[email protected]",
                extra = new Dictionary<string, string>{
                    {"custom_data","custom data"}
                }
            });

FTUnityBridge.UnBindUserdata()

Close SDK

/// <summary>
/// SDK release
/// </summary>

FTUnityBridge.DeInit()

Data Masking

If you want to perform full masking on a field, it is recommended to use SDKConfig.dataModifier, which performs better. If you need detailed rule replacement, SDKConfig.lineDataModifier is recommended.

Single Field Modification (dataModifier)

  • Function: Modifies the value of a single field in the data.
  • Parameter format: {key: newValue}
  • Example: {"device_uuid": "xxx"} will replace the device_uuid field value in the target data with "xxx".

Single Data Line Modification (lineDataModifier)

  • Function: Modifies the value of a specified field in a certain type of data.
  • Parameter format: {measurement: {key: newValue}}
  • Example: {"view": {"view_url": "xxx"}} will modify the view_url field value of all view type data to "xxx".
  • measurement data type list:
    • RUM data: view, resource, action, long_task, error
    • Log data: log
  FTUnityBridge.Install(new SDKConfig
    {
        //...
        dataModifier = new Dictionary<string, object>{
            {"device_uuid","xxx"}
        },
        lineDataModifier = new Dictionary<string, Dictionary<string, object>>
        {
            {"view",new Dictionary<string, object>{
                {"view_url","xxx"}
                }
            }
        }
    });

Native and Unity Hybrid Development

If your project is developed natively, with some pages or business processes implemented using Unity, the SDK installation and initialization configuration methods are as follows:

// FTSDK.cs
IEnumerator _LoadPrefabs()
{
    yield return Instantiate(MainThreadDispatch);
    //_InitSDK();                                 // Cancel initialization
    yield return Instantiate(ViewObserver);
}

Android

iOS

Frequently Asked Questions

Add Prefix to Variables to Avoid Conflict Fields

To avoid conflicts between custom fields and SDK data, it is recommended to add a project abbreviation prefix to tag names, such as df_tag_name. The key values used in the project can be queried from the source code. When the same variable appears in the SDK global variables and RUM/Log, RUM/Log will override the global variable in the SDK.

Others