Skip to content

Unity Application Integration


Prerequisites

Note: If you have enabled the RUM Headless service, the prerequisites have already been automatically configured for you. You can directly proceed with integrating the application.

Application Integration

The current Unity version temporarily supports Android and iOS platforms. Log in to the Guance console, navigate to the "Synthetic Tests" page, click on "Create" in the top-left corner, and start creating a new application.

  1. Input the "Application Name", "Application ID", and select the "Custom" application type.

  2. Application Name: Used to identify the name of the Synthetic Test application.

  3. Application ID: The unique identifier for the application within the current workspace. Corresponding field: app_id. This field only supports English letters, numbers, and underscores, with a maximum of 48 characters.

Installation

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

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

Assets/Plugins
├── Android
│   ├── FTUnityBridge.java                  // Android bridge 
│   ├── ft-sdk-release.aar                  // Android SDK
│   ├── gson-2.8.5.jar                      // Third-party library dependency for Android SDK
├── FTSDK.cs                                // Binding script for FTSDK.prefab
├── FTSDK.prefab                            // Initialization prefab for SDK
├── FTUnityBridge.cs                        // Bridge methods for iOS and Android platforms
├── FTViewObserver.cs                       // Binding script for FTViewObserver.prefab
├── FTViewObserver.prefab                   // Page listener prefab
├── UnityMainThreadDispatcher.cs            // Binding script for UnityMainThreadDispatcher.prefab
├── UnityMainThreadDispatcher.prefab        // Main thread queue prefab
├── iOS
│   ├── FTMobileSDK.framework               // iOS SDK
│   ├── FTUnityBridge.mm                    // iOS bridge
  • Asserts -> Import Package -> Custom Package... Import ft-sdk-unity.unitypackage
  • Add the third-party library for JSON parsing "com.unity.nuget.newtonsoft-json", which can be done via Pakcage Manager -> Add Package by name ...
  • Drag the FTSDK.prefab to the first scene page and initialize the SDK in the _InitSDK method of FTSDK.cs. If the native Android and iOS projects have already integrated the native SDK, comment out the _InitSDK method to avoid redundant settings.
  • Drag the FTViewObserver.prefab to other scene pages to achieve lifecycle monitoring of the View pages, including app suspension and wake-up.
  • Use Application.logMessageReceived to listen and convert Unity crash data and regular log data; see the OnEnable and OnDisable methods in FTSDK.cs.

Note: If the native SDK for Android (gson-2.8.5.jar, ft-sdk-release.aar) and iOS (FTMobileSDK.framework) are already integrated into the project, they can be removed from the project. Additionally, for Android Okhttp request and startup duration features, use ft-plugin for detailed configuration; see Android SDK.

Initialization

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

            });
Field Type Required Description
serverUrl string Yes Datakit access URL address, example: http://10.0.0.1:9529, default port 9529. Note: The device where the SDK is installed must be able to access this address.
env string No Environment, default prod. prod: production environment; gray: gray environment; pre: pre-release environment; common: daily environment; local: local environment, custom values supported.
debug bool No Whether to enable debugging mode.
globalContext dictionary No Add global attributes to the SDK, rules for adding please refer to here.
serviceName string No Affects the service field data in Logs and RUM, default for Android is df_rum_android, for iOS is df_rum_ios.

RUM Configuration

FTUnityBridge.InitRUMConfig(new RUMConfig()
            {
                androidAppId = "androidAppId",
                iOSAppId = "iOSAppId",
                sampleRate = 0.8f,
            });
Field Type Required Description
androidAppId string Yes Corresponding setting for RUM appid, required to enable RUM collection, method to obtain appid.
iOSAppId string Yes Corresponding setting for RUM appid, required to enable RUM collection, method to obtain appid.
sampleRate float No Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default value is 1. Applies to all View, Action, LongTask, Error data under the same session_id.
globalContext dictionary No Add label data to distinguish user monitoring data sources. If tracking functionality is needed, the parameter key should be track_id, and value can be any number. Rules for adding please refer to here.
enableNativeUserAction bool No Whether to enable Native Action collection, default false.
enableNativeUserView bool No Whether to enable Native View collection, default false.
enableNativeUserResource bool No Whether to enable Native Resource collection, Android supports Okhttp, iOS uses NSURLSession, default false.
extraMonitorTypeWithError enum No Add additional monitoring data to Rum crash data, memory for memory usage, cpu for CPU occupancy rate, all for all.
deviceMonitorType enum No Additional page monitoring types: all, battery (only supported on Android), memory, cpu, fps.
detectFrequency enum No Page monitoring frequency: normal (default), frequent, rare.

Log Configuration

FTUnityBridge.InitLogConfig(new LogConfig
            {
                sampleRate = 0.9f,
                enableCustomLog = true,
                enableLinkRumData = true,
            });
Field Type Required Description
sampleRate float No Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default value is 1.
globalContext dictionary No Add label data, rules for adding please refer to here.
logLevelFilters array No Set log level filters, ok, info, warning, error, critical, default does not filter.
enableCustomLog bool No Whether to upload custom logs, default is false.
discardStrategy enum No discard discards appended data, discard_oldest discards old data, default is discard.

Trace Configuration

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

            });
Field Type Required Description
sampleRate float No Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default value is 1.
traceType enum No Default is ddtrace, currently supports zipkin, jaeger, ddtrace, skywalking (8.0+), traceParent (W3C). When connecting OpenTelemetry, choose the corresponding chain type and check the supported types and agent-related configurations.
enableLinkRUMData bool No Whether to link with RUM data, default is false.

RUM User Data Tracking

Currently, RUM data transmission can only be achieved through manual method calls.

Action

Usage Method

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

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

Code Example

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

View

Usage Method

/// <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 attribute 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 attribute parameters</param>
public static void StopView(Dictionary<string, object> property)

Code Example

FTUnityBridge.StartView("TEST_VIEW_ONE");

FTUnityBridge.StopView();

Resource

Usage Method

/// <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 attribute 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 attribute 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 metrics data</param>
public static async Task AddResource(string resourceId, ResourceParams resourceParams, NetStatus netStatus)
NetStatus
Method Name Type Required Description
fetchStartTime long No Request start time, ns
tcpTime long No TCP connection duration, ns
dnsTime long No DNS resolution time, ns
responseTime long No Content transfer duration, ns
sslTime long No SSL connection duration, ns
firstByteTime long No Total time from DNS resolution to receiving the first packet, ns
ttfb long No Time from sending the request to receiving the first packet, ns
tcpStartTime long No TCP connection start time, ns
tcpEndTime long No TCP connection end time, ns
dnsStartTime long No DNS resolution start time, ns
dnsEndTime long No DNS resolution end time, ns
responseStartTime long No Response start time, ns
responseEndTime long No Response end time, ns
sslStartTime long No SSL start time, ns
sslEndTime long No SSL end time, ns
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";
NetStatus netStatus = new NetStatus();
netStatus.fetchStartTime = DateTimeOffset.Now.ToUnixTimeMilliseconds() * 1000000;

FTUnityBridge.AddResource(resourceId, resourceParams, netStatus);

Error

Usage Method

/// <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 attribute 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 Method

/// <summary>
/// Add a long-duration 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 a long-duration task
/// </summary>
/// <param name="log">Log content</param>
/// <param name="duration">Duration, nanoseconds</param>
/// <param name="property">Additional attribute 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 Logging

Current log content limit is 30 KB, exceeding characters will be truncated.

Usage Method

/// <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 attribute parameters</param>
/// <returns></returns>
public static async Task AddLog(string log, LogLevel level, Dictionary<string, object> property)

LogLevel

Method Name Meaning
info Prompt
warning Warning
error Error
critical Severe
ok Recovery

Code Example

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

Tracer Network Chain Tracking

Chain tracking is achieved by generating a Trace Header and then adding the Header to the HTTP request header.

Usage Method

/// <summary>
/// Get chain Id
/// </summary>
/// <param name="url">URL address</param>
/// <returns>JSON character</returns>
public static async Task<string> GetTraceHeaderWithUrl(string url)


/// <summary>
/// Get chain
/// </summary>
/// <param name="resourceId">Resource Id</param>
/// <param name="url">URL address</param>
/// <returns>JSON character</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);

User Information Binding and Unbinding

Usage Method

/// <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 KV assignment, rules for adding please refer to here

Code Example

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

FTUnityBridge.UnBindUserdata()

Close SDK

/// <summary>
/// SDK release
/// </summary>
public static void DeInit()

Code Example

FTUnityBridge.DeInit()

Android

iOS

FAQs

Adding Local Variables to Avoid Field Conflicts

To avoid conflicts between custom fields and SDK data, it is recommended to prefix tag names with project abbreviations, such as df_tag_name. In the project, the key values used can be queried from source code. If variables in the SDK global variables conflict with those in RUM or Logs, RUM and Logs will override the global variables in the SDK.

Others

Feedback

Is this page helpful? ×