• 1 Unity C# Integration
  • 2 Unity Integration in System Native Layer
  • 3 C# Interfaces (Android&iOS)
  • 4 C# Interfaces (Windows)

Unity SDK Integration


This document applies to the current stable version, Android, iOS and Windows platforms can refer to this document to integrate. Xbox, PS4, PS5, Switch and Linux platforms can refer to the new version of Unity SDK Integration Document

1 Unity C# Integration

1.1 Download and Import Unity Plugin to Unity Project

After creating a project on the platform, the SDK that matches the platform and engine of the project can be downloaded from the "Tutorial" in the sidebar, as shown in the figure below:

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);
#elif UNITY_STANDALONE_WIN
        CrashSightAgent.InitContext(UserId, AppVersion, CrashSightAppKeyForWindows);
// UserId and AppVersion can be decided by yourself according to your needs, and APP Key can be found in More->Product Settings->Product Information of the management terminal.
#endif

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
    • iiii. MetricKit.framework for obtaining app diagnostic information provided by apple

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 Windows

After the project is packaged, find CrashSight64.dll under _Data\Plugins\x86_64 in the packaged file, and create a TQM64/dump directory and a GameBabyConfig64.dat file (create a new text file, then change the suffix) in the same level directory. There are three parameters to be updated in the GameBabyConfig64.dat file:

1)GameName
2)Reported URL
3)APPID

<GameBabyConfig __version="1">
	<GameName>Test-Game.exe</GameName>
	<LobbyName></LobbyName>
	<IgnoreDllCnt>2</IgnoreDllCnt>
	<IgnoreDlls>TenSLX.dll</IgnoreDlls>
	<IgnoreDlls>Tensafe.dll</IgnoreDlls>
	<AppId>0620edc732</AppId>
	<DomainUrl>pc.crashsight.qq.com</DomainUrl>
</GameBabyConfig>

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) 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
  • 3) 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 (Android)

static void TestJavaCrash();

Test Object-C crash (iOS)

static void TestOcCrash();

Test Native crash (Android&iOS)

static void TestNativeCrash();

Force Unity crash (Windows)

UnityEngine.Diagnostics.Utils.ForceCrash(ForcedCrashCategory.AccessViolation);

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.6.3 Testing Method for Windows

  • a.Verify if CrashSight can connect to the internet and report normally. The verification process is:

    1. Initialize CrashSight;
    2. Wait 5 minutes and go to Exception Overview --> Crash Tendency --> Number of Devices Connected in the management console. The stats should be equal to or higher than 1.
  • b.Verify if a crash can be reported normally. The verification process is:

    1. Initialize CrashSight;
    2. You can trigger a crash in the game using the following code. (You can also use other bad memory access methods)
    int* a = 0;
    a[10000] = 5;
    
  • c.See if there is a generated dmp file under TQM64/dump. The crash is not successfully captured if you are unable to find the file. In this case, please contact CrashSight developer.

  • d.Go to "Crash Analysis" in the management console and see if there is a report with the corresponding time stamp. If you see the dmp file in step 3 but are unable to find the report in step 4, the crash was not successfully reported. Please check APPID config (Both config files need to be correct) and the APP KEY config if they correspond to each other and are the same in the application config. If it still fails to report using the correct config, please contact CrashSight developers.

  • e.Check if the version number and the user name of the crash report is the same as the configuration.

  • f.Check if the version number and the user name of the error report is the same as the configuration.

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 seeSymbol Table Uploading Tools Guide

2 Unity Integration in System Native Layer

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.

2.1 Download and Import Unity Plugin to Unity Project

Download Plugin open in new windowopen in new window(Download is unavailable due to an ongoing internal review. To download it, please contact crashsight@tencent.com), 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

2.2.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);
}

2.2.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);

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 (Android&iOS)

3.1 Initialization

public static void InitWithAppId (string appId)

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

ParameterTypeNote
appIdstringAPP 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.

ParameterTypeNote
enableboolEnabling 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.

ParameterTypeNote
crashServerUrlstringTarget 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.

ParameterTypeNote
typeintIgnore it. Just enter 0.
logLevelintOff=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.

ParameterTypeNote
deviceIdstringDevice ID

3.6 Set Phone Model

public static void SetDeviceModel(string deviceModel)

Note: Set phone model

Note: Call it before the InitWithAppId interface.

ParameterTypeNote
deviceModelstringPhone 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

ParameterTypeNote
eSystem.ExceptionC# exception
messagestringException 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

ParameterTypeNote
typeintException type, C#: 4, js: 5, lua: 6
exceptionNamestringException Name
exceptionMsgstringException Info
exceptionStackstringStack
extInfoDictionary<string, string>Other Info

View page:

extInfo: Crash Details->Download Attachments->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

ParameterTypeNote
typeintException type, C#: 4, js: 5, lua: 6
exceptionNamestringException Name
exceptionMsgstringException Info
exceptionStackstringStack
extInfoDictionary<string, string>Other Info
isDumpNativeStackboolwhether to dump the Native stack of the current thread

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

AndroidiOS
Attachment sizeDump stackDo not dump stackDump stackDo 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

ParameterTypeNote
userIdstringUser ID

3.11 Mark a Scene

public static void SetScene(int sceneId)
ParameterTypeNote
sceneIdintScene 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. Supports use in callbacks.

View page: Crash Details->Download Attachments->valueMapOthers.txt

ParameterTypeNote
keystringKey
valuestringValue

3.13 Set App Version

public static void SetAppVersion(string appVersion)

Note: Set app version, which must be called before initialization.

ParameterTypeNote
appVersionstringVersion 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. Android does not support writing custom logs in crash callbacks.

ParameterTypeNote
levelCSLogSeverityLog level
formatstringLog format
argsparams 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.

3.18 Set Android Logcat Size

public static void SetLogcatBufferSize(int size)

Note: Set the size of logcat logs uploaded on crashes and errors, valid only for Android. It is recommended to set it less than 128KB. The default value is 30KB.

ParameterTypeNote
sizeintLogcat log size in bytes

4 C# Interfaces (Windows)

4.1 Initialization

public static void InitContext(string userId, string version, string key)

Note: Performs initialization. Perform initialization at the earliest possible location to enable crash capture and reporting.
The user Id and version number can be determined by the user and they will be reported along with the crash reporting.

ParameterTypeNote
userIdstringUser Id
versionstringVersion
keystringAPP key of registered project

4.2 Proactive C# Exception Reporting

public static void ReportException(int type, string name, string message, string stackTrace, string extras, bool quitProgram)

Note:Report a C# Exception

ParameterTypeNote
typeintexception type, C#: 4, js: 5, lua: 6
namestringexception name
messagestringexception message
stackTracestringexception stack
extrasstringextra information
quitProgramboolquit program
public static void ReportException(int type, string exceptionName, string exceptionMsg, string exceptionStack, Dictionary<string, string> extInfo)

Note:Report a C# Exception

ParameterTypeNote
typeintexception type, C#: 4, js: 5, lua: 6
exceptionNamestringexception name
exceptionMsgstringexception message
exceptionStackstringexception stack
extInfoDictionary<string, string>extra information

4.3 Add Custom Data

public static void AddSceneData(string key, string value)

Note: Set user-defined Key-Value data, which will be reported with the exception message when sending Crash, the length of a single key is limited to 100 characters, and the length of a single value is limited to 1000 characters.

View in webpage: Crash detail page -> Value Map

ParameterTypeNote
keystringkey
valuestringvalue

4.4 Set Custom Log Path

public static void SetCustomLogDir(string path)

View in webpage: Crash detail page -> Custom Log (via File)

ParameterTypeNote
pathstringlog path

4.5 Set User ID

public static void SetUserId(string userId)

Note: Set user ID. Please call it after initialization.

ParameterTypeNote
userIdstringUser ID

4.6 Add Custom Log

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

Note: Customized log with a limit of 30KB

ParameterTypeNote
levelCSLogSeveritylog level
formatstringlog format
argsparams object[]variable arguments
Last Updated: