Pricing
Unity SDK Integration
Help Documents menu

Unity SDK Integration

Updated on: 2023-02-15 19:11

1 Unity C# Integration

1.1 Download and Import Unity Plugin to Unity Project

  • Download Plugin (Download is unavailable due to an ongoing internal review. To download it, please contact WeTest@wetest.net), double-click the .unitypackage file in the plugin bundle, import files related to Plugins to the Unity project. (If a plugin bundle of an earlier version is in use, make sure to delete its files).

1.2 Initialize CrashSight

Choose the first scene or the main scene, and call the following code in a script loaded as early as possible to initialize:

// TODO NOT Required. Enable debug log print, please set false for release version
// Debug switch. In the debugging mode, more logs will be printed to locate issues.

#if DEBUG
        CrashSightAgent.ConfigDebugMode (true);
#endif
        CrashSightAgent.ConfigDebugMode (false);

#if UNITY_IPHONE || UNITY_IOS
//  Set the target domain name to report to. Please fill in according to project requirements. (required)
        CrashSightAgent.ConfigCrashServerUrl(CrashSightUploadUrliOS);
// Set the target APP ID for reporting and initialize. You can find the APP ID from More->Product Settings->Product Info of the management console.
        CrashSightAgent.InitWithAppId(CrashSightAppIDForiOS);
#elif UNITY_ANDROID
        CrashSightAgent.ConfigCrashServerUrl(CrashSightUploadUrlAndroid);
        CrashSightAgent.InitWithAppId(CrashSightAppIDForAndroid);
#endif

        // TODO Required. If you do not need call 'InitWithAppId(string)' to initialize the sdk(may be you has initialized the sdk it associated Android or iOS project),
        // please call this method to enable c# exception handler only.
        CrashSightAgent.EnableExceptionHandler ();

Domain name for reporting

Domestic public cloud:

  • Android: https://android.crashsight.qq.com/pb/async
  • iOS: https://ios.crashsight.qq.com/pb/sync

Overseas public cloud

  • Android: https://android.crashsight.wetest.net/pb/async
  • iOS: https://ios.crashsight.wetest.net/pb/sync

1.3 Integration Configurations for iOS

  • 1)Change the project’s preferences in Unity (Build Settings) a. Press Ctrl+Shift+B to open the Build Settings panel. Click Player Settings and switch to the Setting for iOS tab. Choose the Other Settings bar, and change the Script Call Optimization of Optimization to Slow and Safe.
  • 2)Change the compilation configuration of the exported Xcode project. Switch to the Build Phases tab, and add the following dependencies under Link Binary With Libraries:
    • i. libz.dylib is for compressing reported data
    • ii. Security.framework is for storing keychain
    • iii. SystemConfiguratiom.framework is for reading system info in case of an exception

Note:

  • i. If these dependencies have been added to the project, no need to add them again.
  • ii. If XUPorter is used to integrate, there’s no need to add configuration items in Xcode.

1.4 Integration Configurations for Android

Change permission settings in the AndroidManifest.xml configuration file of the Android project.

<!-- network communication-->
<uses-permission android:name= "android.permission.INTERNET" />
<!-- obtain network status-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- obtain MAC address-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

1.5 Unity Integration Demo

  • 1)Double-click the CrashSightPlugin.unitypackage package in the downloaded plugin. The following screen will appear in Unity. Import the plugin.
  • 2)Edit the AndroidManifest.xml configuration file and configure the corresponding permissions.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
  • 3) Initialize.
private const string CrashSightAppIDForiOS = "685a68759e";
private const string CrashSightAppIDForAndroid = "e6af377f84";
private const string CrashSightUploadUrliOS = "https://ios.crashsight.qq.com/pb/sync";
private const string CrashSightUploadUrlAndroid = "https://android.crashsight.qq.com/pb/async";

CrashSightAgent.ConfigDebugMode (true);
#if UNITY_IPHONE || UNITY_IOS
        CrashSightAgent.ConfigCrashServerUrl(CrashSightUploadUrliOS);
        CrashSightAgent.InitWithAppId(CrashSightAppIDForiOS);
#elif UNITY_ANDROID
        CrashSightAgent.ConfigCrashServerUrl(CrashSightUploadUrlAndroid);
        CrashSightAgent.InitWithAppId(CrashSightAppIDForAndroid);
#endif
 CrashSightAgent.EnableExceptionHandler ();
  • 4) Integration for iOS is similar to that of Android, but the project must be packed as an Xcode project and configurations should be done in the Xcode project.

1.6 Integration Result Testing

CrashSight Test Interface

Test Java crash

static void TestJavaCrash();

Test Object-C crash

static void TestOcCrash();

Test Native crash

static void TestNativeCrash();

1.6.1 Testing Method for iOS

  • a. Enable Debug mode. Initialize CrashSight and assign suitable config parameters.
  • b. Network and report: Check if “begin to upload <CSAnalyticsLogic” or “cmd: 641” is printed in the test device log.
  • c. Crash detection: Check if “Handle the crash scene in callback” is printed in the test device log.
  • d. Report exceptions: Check if “begin to upload <CSCrashLogic” or “cmd: 631” is printed in the test device log.

1.6.2 Testing Method for Android

  • a. Enable Debug mode. Initialize CrashSight and assign suitable config parameters.
  • b. Network and report: Check if “[Upload] Run upload task with cmd: 840” is printed in the logcat log.
  • c. Crash detection: Check if “HandleSignal start” is printed in the logcat log.
  • d. Report exception: Check if “[Upload] Run upload task with cmd: 830” is printed in the logcat log.

1.7 Upload Symbol Table

The above is an introduction to SDK Integration, crash reporting and verifying, but to see readable restored stacks on the page, you need to upload the corresponding symbol table. Please see Symbol Table Uploading Tools Guide

2 Unity Integration in System Native Layer

2.1 Download and Import Unity Plugin to Unity Project

Download Plugin open in new window (Download is unavailable due to an ongoing internal review. To download it, please contact WeTest@wetest.net), double-click the .unitypackage file in the plugin bundle, import files related to Plugins to the Unity project. (If a plugin bundle of an earlier version is in use, make sure to delete its files).

2.2 SDK Initialization

Refer to CrashSight’s SDK Integration in mobile devices. Complete the initialization for iOS and Android in the native layer.

2.3 Re-registration for Android

Due to compatibility issues of Unity 5 and later versions, after initializing in the native layer, a re-registration using C# is required for Android. iOS doesn’t require it at present. Re-registration function: CrashSightAgent.ReRegistAllMonitors(); Execute this function as early as possible in the C# layer script.

2.4 Report Unity Log Error (Optional)

If the project wants to report Unity Log Error to CrashSight as an error, the feature can be enabled by calling CrashSightAgent.EnableExceptionHandler(); note that the triggering frequency of Unity Log Error in the project should be kept low after enabling the feature.

2.5 Callback in Case of a Crash/an Error (Optional)

If the project wants some content to be added into the report in case of a crash/an error, it can be added by processing callbacks. Note that:

    1. Keep the thread safe during callbacks so that there won’t be a second crash. If a second crash happens, the current crash won’t be reported this time. If conditions permit, it will be reported the next time the project is activated, but the callback won’t be included in the report.
    1. Callback info must comply with compliance requirements.

3 C# Interfaces

3.1 Initialization

public static void InitWithAppId (string appId)

Note: Execute initialization. Initialize as early as possible to enable crash detection and reporting features.

Parameter Type Note
appId string APP ID of registered projects

3.2 Debug Switch

public static void ConfigDebugMode (bool enable)

Note: Whether to enable debugging mode. Off by default. After enabling, some logs will be printed, but it can help locate issues during tests.
Note: Call it before the InitWithAppId interface.

Parameter Type Note
enable bool Enabling switch for debugging

3.3 Set Domain Name for Reporting

`public static void ConfigCrashServerUrl (string crashServerUrl)`

Note: Set domain name for reporting.
Note: Call it before the InitWithAppId interface.
The domain name of domestic public environment is as follows:

  • Android: https://android.crashsight.qq.com/pb/async
  • iOS: https://ios.crashsight.qq.com/pb/sync

A direct CrashSight domain name Integration is different from an indirect one using MSDK. Make sure you follow the above domain name to reconfigure. For other environment domain name, please consult the Integration contact.

Parameter Type Note
crashServerUrl string Target domain name of reporting

3.4 Set Log Reporting Level

public static void ConfigCrashReporter(int type, int logLevel)

Note: Set log reporting level

Note: Call it before the InitWithAppId interface.

Parameter Type Note
type int Ignore it. Just enter 0.
logLevel int Off=0,Error=1,Warn=2,Info=3,Debug=4

3.5 Set Device ID

public static void SetDeviceId(string deviceId)

Note: Starting from version 4.2.9, CrashSight Android no longer obtains AndroidId, and uses uuid as device ID by default

Note: Call it before the InitWithAppId interface.

Parameter Type Note
deviceId string Device ID

3.6 Set Phone Model

public static void SetDeviceModel(string deviceModel)

Note: Set phone model

Note: Call it before the InitWithAppId interface.

Parameter Type Note
deviceModel string Phone model

3.7 Exception Enabling Switch Using C#

public static void EnableExceptionHandler ()

Note: Enables C# exception reporting and LogError logs. If you didn’t call the “InitWithAppId(string)” interface in C# to initialize, you can call this interface separately.

3.8 Active C# Exception Reporting

public static void ReportException (System.Exception e, string message)

Note: Active C# exception reporting

Parameter Type Note
e System.Exception C# exception
message string Exception Info

3.9 Active C# Error Reporting

public static void ReportException(int type, string exceptionName, string exceptionMsg, string exceptionStack, Dictionary<string, string> extInfo)

Note: Active C# error reporting

Parameter Type Note
type int Exception type, C#: 4, js: 5, lua: 6
exceptionName string Exception Name
exceptionMsg string Exception Info
exceptionStack string Stack
extInfo Dictionary<string, string> Other Info

View page:

extInfo: Crash Details->Trace Data->extraMessage.txt

public static void ReportException(int type, string exceptionName, string exceptionMsg, string exceptionStack, Dictionary<string, string> extInfo, bool isDumpNativeStack)

Note: Active C# error reporting

Parameter Type Note
type int Exception type, C#: 4, js: 5, lua: 6
exceptionName string Exception Name
exceptionMsg string Exception Info
exceptionStack string Stack
extInfo Dictionary<string, string> Other Info
isDumpNativeStack bool whether to dump the Native stack of the current thread

View page:
extInfo: Crash Details->Trace Data->extraMessage.txt
Native stack: Crash Details->Trace Data->trace.zip
Other: time used to report the error

Android iOS
Attachment size Dump stack Do not dump stack Dump stack Do not dump stack
100K [0.207000]s [0.001554]s [0.114835]s [0.001172]s
10K [0.204285]s [0.000223]s [0.107594]s [0.000382]s
1K [0.140075]s [0.000151]s [0.105755]s [0.000365]s

3.10 Set User ID

public static void SetUserId(string userId)

Note: Set User ID

Parameter Type Note
userId string User ID

3.11 Mark a Scene

public static void SetScene(int sceneId)
Parameter Type Note
sceneId int Scene ID

3.12 Add Custom Data

public static void AddSceneData(string key, string value)

Note: Set the Key-Value data customized by the user. It will be reported together with exception info when sending the crash. Each key shouldn’t exceed 100 characters, each value shouldn’t exceed 1000 characters, and the total length (all keys+all values) shouldn’t exceed 64KB for Android, 128KB for iOS.

View page: Crash Details->Trace Data->valueMapOthers.txt

Parameter Type Note
key string Key
value string Value

3.13 Set App Version

public static void SetAppVersion(string appVersion)

Note: Set app version

Parameter Type Note
appVersion string Version Number

3.14 Add Custom Log

public static void PrintLog(CSLogSeverity level, string format, params object[] args)

Note: The custom log shouldn’t exceed 30KB.

Parameter Type Note
level CSLogSeverity Log level
format string Log format
args params object[] Variadic parameter

3.15 Re-register

public static void ReRegistAllMonitors()

Note: Re-register the signal capture function

3.16 Set Callback

public static void RegisterCrashCallback(CrashSightCallback callback)

Note: called in case of a crash. The returned value will be reported along with crash info. Customize the CsCrashCallBack class, inherit CrashSightCallback, and use the OnCrashBaseRetEvent method

public class CsCrashCallBack: CrashSightCallback  {
    // Put you own code to implemente the callback func
    public override string OnCrashBaseRetEvent(int methodId)
    {
        if (methodId == (int)UQMMethodNameID.UQM_CRASH_CALLBACK_EXTRA_MESSAGE)
        {
            return "this is extra message.";
        }
        return "";
    }
}

The callback content for Android is on the “Crash Analysis-Trace Data-extraMessage.txt” page. The callback content for iOS is on the “Crash Analysis-Trace Data-crash_attach.log” page.

3.17 Set Log Uploading Callback

public static void RegisterCrashLogCallback(CrashSightLogCallback callback);

Note: Called after handling a crash. Customize the CsCrashLogCallback class, inherit CrashSightLogCallback, and use OnSetLogPathEvent and OnLogUploadResultEvent methods

public class CsCrashLogCallBack : CrashSightLogCallback
{
    // Returns the log file's absolute path
    // methodId Method ID. The business can ignore it
    // crashType Crash type, 0: Java/Objective-C crash, 2: native crash
    public override string OnSetLogPathEvent(int methodId, int crashType)
    {
        return "";
    }

    // Shows the result of log file uploading
    // methodId Method ID. The business can ignore it
    // result Result of uploading 0: successful, other: failed
    public override void OnLogUploadResultEvent(int methodId, int crashType, int result)
    {
        
    }
}

The callback content for Android is on the “Crash Analysis-Trace Data-Client Uploading Log” page. The callback content for iOS is on the “Crash Analysis-Trace Data-Client Uploading Log” page.

4 Early Unity Initialization

Background

Delayed C# layer initialization and registration of the signal handling function may render the detection of previous crashes unavailable. Therefore, it’s recommended to initialize and register signal early.

4.1 Early Initialization for Android Using Java

EditUnityPlayerActivity.java

Import header file

import com.uqm.crashsight.core.api.CrashSightPlatform;
import com.uqm.crashsight.core.api.crash.UQMCrash;
import com.uqm.crashsight.core.tools.NDKHelper;
import com.uqm.crashsight.core.tools.UQMLog;
import com.uqm.crashsight.crashreport.CrashReport;
import com.uqm.crashsight.crashreport.CrashSightLog;

Call the interface initializing function init with the onCreate function

init("https://android.crashsight.qq.com/pb/async", "39bdeb63a2", true);

How to use the init function:

public void init(String mCrashUploadServerUrl, String appId, boolean mDebugMode) {
        if (mCrashUploadServerUrl != null) {
            CrashReport.setServerUrl(mCrashUploadServerUrl);
        }
        Context context = CrashSightPlatform.getActivity();
        if (context != null) {
            if (NDKHelper.loadSO()) {
                UQMLog.e("CrashSightCore.so is loaded successfully");
            } else {
                UQMLog.e("CrashSightCore.so is loaded failed");
                return;
            }
        }  else {
            UQMLog.e("CrashSight platform get activity failed.");
            return;
        }
        // Configure user strategies
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);

        // Set callbacks (For the C# layer, the interface for setting the callback function should be called)
        strategy.setCrashHandleCallback(new CrashReport.CrashHandleCallback() {
            @Override
            public synchronized Map<String, String> onCrashHandleStart(int crashType, String errorType, String errorMessage, String errorStack) {
                // Obtain custom info Map of parent class
                Map<String, String> userData = super.onCrashHandleStart(crashType, errorType, errorMessage, errorStack);
                if (userData == null) {
                    userData = new HashMap<>();
                }
                // Call the callback function set by the user and obtain extra info reported by Crash
                try {
                    String extraMessage = UQMCrash.attachmentMessageForException(crashType);
                    if (extraMessage.length() > 0) {
                        UQMLog.d("CrashSight extra message report ok, message : " + extraMessage);
                        userData.put("extmsg", extraMessage);
                    } else {
                        UQMLog.d("CrashSight extra message is empty");
                    }
                } catch (Exception e) {
                    UQMLog.e("onCrashHandleStart extra message report error, message : " + e.getMessage());
                }
                return userData;
            }
            @Override
            public byte[] onCrashHandleStart2GetExtraDatas(int crashType, String errorType, String errorMessage, String errorStack) {
                try {
                    // Call the callback function set by the user and obtain extra info reported by Crash
                    byte[] extraBinaryMessage = UQMCrash.attachmentForException(crashType);
                    if (extraBinaryMessage != null && extraBinaryMessage.length > 0) {
                        UQMLog.d("CrashSight extraBinaryMessage data report ok");
                        return extraBinaryMessage;
                    } else {
                        UQMLog.d("CrashSight extraBinaryMessage data is empty");
                        return null;
                    }
                } catch (Exception e) {
                    UQMLog.e("onCrashHandleStart2GetExtraData exception, message : " + e.getMessage());
                    return null;
                }
            }
        });

        // Initialize CS
        CrashReport.initCrashReport(context, appId, mDebugMode, strategy);
}

4.2 Early Initialization for iOS Using Objective-C

EditUnityAppController.mm

Import header file

#import <CrashSight/CrashSight.h>
#import <CrashSight/CrashSightConfig.h>
#import <CrashSightCore/CrashSightCore.h>

Implement protocol

@interface UnityAppController()<CrashSightDelegate>
@end
// Customize the max callback massage length (up to 128KB at present)
#define UQM_CRASHSIGHT_MAX_LEN_EXCEPTION_ATTACH_MESSAGE  (1024 * 128)
// Use namespace
USING_NS_UQM

Implement the callback interface in the protocol

/**
 * Exception callback function
 *
 * @param exception  exception Exception info
 * @return           Info to be added
 */
- (NSString *)attachmentForException:(NSException *)exception callbackType:(CSCallbackType)callbackType{
    UQM_LOG_DEBUG("attachmentForException invoked");
    // Use a synchronous method to call and obtain additional info of game settings
    UQMInnerCrashRet ret;
    ret.methodNameID = kUQMMethodNameCrashExtraMessage;
    // Assign the space for data storing
    ret.data = UQM_SAFE_MALLOC(UQM_CRASHSIGHT_MAX_LEN_EXCEPTION_ATTACH_MESSAGE, char);
    // Set the max length
    ret.maxDataLen = UQM_CRASHSIGHT_MAX_LEN_EXCEPTION_ATTACH_MESSAGE;
    std::memset(ret.data, 0, UQM_CRASHSIGHT_MAX_LEN_EXCEPTION_ATTACH_MESSAGE);
    // Set the crash type
    ret.crashType = (int) callbackType;
    // It's a synchronous method that calls the callback function set by the user and obtains info added by the user, which is essentially ret.data.
    UQMInnerObserverHolder<UQMInnerCrashRet>::CommitToTaskQueueBackRet(ret, kUQMMethodNameCrashExtraMessage, "");
    if (strlen(ret.data) == 0) {
        return nil;
    }
    UQM_LOG_DEBUG("attachmentForException message : %s", ret.data);
    return [NSString stringWithUTF8String:ret.data];
}

Initialize viadidFinishLaunchingWithOptions

// Initialize CrashSight
// Obtain CrashSight configurations and initialize
CrashSightConfig * config = [[CrashSightConfig alloc] init];
config.unexpectedTerminatingDetectionEnable = YES;
config.debugMode = true;
config.reportLogLevel = CrashSightLogLevelVerbose;
config.crashServerUrl = @"https://ios.crashsight.qq.com/pb/sync";

config.delegate = self;

[CrashSight startWithAppId:@"1f29ad1a5a" config:config];

UQM_LOG_DEBUG("CrashSight appid :%s , version :%s","1f29ad1a5a", [CrashSight sdkVersion].UTF8String);