目录
此内容是否有帮助?

# History Version Unity SDK Usage Guide

The Unity SDK has been upgraded to v2.0.0. This article is a guide to the use of historical versions. If you need new access, please refer to the latest Unity SDK use guide

This guide describes how to access your project using the Unity SDK. It is recommended to read the Data Rules chapter before accessing. You can get the Unity SDK source code at GitHub (opens new window).

**The latest version is: **v1.4.4

**Updated: **2020-04-17

Download address (opens new window)

# I. Initialize SDK

# 1.1 Integrated SDK

  1. Download the Unity SDK (opens new window)resource file and import the resource file into your project: Assets > Import Package > Custom Package, select the file you just downloaded

    Note: The Android plug-in uses Gradle integration, so currently only Unity 5.4 and later versions are supported.

  2. Add ThinkingAnalytics GameObject and set SDK configuration

The configurations in the above figure are:

Configuration

  • Enable Log: Whether to turn on the log, if so, the report will be printed to facilitate your debugging. You can also verify that events are reported correctly in Editor mode. For unqualified attributes, a warninglog will be displayed in the console.
  • Network Type: Set the network conditions for reporting data to the server. The default is DEFAULT. The following are all options and corresponding instructions:
    • DEFAULT: Reporting data in 3G, 4G, 5G and WIFI environments
    • WIFI: only report data in WIFI environment
    • ALL: Reporting data in 2G, 3G, 4G, 5G and WIFI environments
  • Postpone Track: Set whether to delay reporting. After this option is turned on, the data will not start reporting until StartTrack ()is called. The data will be cached before the call until StartTrack ()is called. **If you need to set the guest ID or public attributes, it is recommended that you turn this on **, please refer to the delayed reporting section for invocation

Tokens

Each Token identifies an instance. If you need to report data to multiple projects, you can click the '+' sign in the lower right corner to increase the project configuration. For multi-project precautions, please refer to the 'Multi-Project Support' section at the end of the section. You can add multiple Token configurations with different APP IDs.

  • The APP_ID of your project will be given when you apply for the project, please fill in here.
  • SERVER URL: Need to be configured for the URL of the data receiving end:
    • If you are using Cloud as a Service, enter the following URL:
      • https://receiver.ta.thinkingdata.cn
    • If you are using the version of private deployment, enter the following URL:
      • https://Data Acquisition Address
  • MODE: SDK instance operation mode. Please use NORMAL mode for the generation environment. Please refer to SDK mode for details.
  • Auto Track: Whether to turn on automatic collection events. If checked, the SDK will automatically record the start and close of the game. For details, please refer to automatic collection events
  • TimeZone: Supported since v1.4.3, the default alignment time zone for data. This setting is currently only valid for the event time and the time set by the user feature, not for the DateTime type in the property.

    Note: Since some devices prohibit plaintext transmission by default, it is strongly recommended that you use the receiving end address in HTTPS format.

# Multi-project Support

When configuring the SDK, you can add multiple APP IDs, and then when calling the API, finally attach a parameter to specify the APP ID. Take the Identify ()interface as an example:

// Set the visitor ID for the APP ID instance of "debug-appid"
ThinkingAnalyticsAPI.Identify("unity_debug_id", "debug-appid");

Note: Visitor IDs, account IDs, public attributes, etc. are not shared among multiple projects, and need to be set separately for each APP ID instance.

If no APP ID parameter is attached, the first APP ID instance in the list is used by default (the instance identified by default after the Token ID). You can adjust the default APP ID instance by dragging the list items to adjust the list order.

# 1.2 Use the SDK

Once you have finished configuring the SDK, you can start uploading events using the SDK, and we have provided Samples for your reference.

using ThinkingAnalytics;

ThinkingAnalyticsAPI.Track("unity_start");

# II. Set User ID

After using the Unity SDK, the SDK will use random UUID as the guest ID of each user by default, and this ID will be used as the user's identification ID when the user is not logged in. It should be noted that the default guest ID will change when the user reinstates the game and changes the device.

# 2.1 Set Visitor ID (optional)

If your game has its own guest ID management system for each user, you can call Identifyto set the guest ID:

ThinkingAnalyticsAPI.Identify("unity_id");

If you need to get a guest ID, you can call GetDistinctIdto get:

ThinkingAnalyticsAPI.GetDistinctId();

# 2.2 Set and Clear Account ID

When the user logs in, you can call Loginto set the user's account ID. After setting the account ID, the account ID will be used as the user identification ID, and the set account ID will be called LogoutIt has been retained until:

// Set Account ID
ThinkingAnalyticsAPI.Login("unity_user");

// Clear Account ID
ThinkingAnalyticsAPI.Logout();

Note: This method does not upload user login, user login and other events.

# III. Upload Events

The ThinkingAnalytics API. Track ()allows you to report events and their properties. In general, you may need to upload a dozen to hundreds of different events. If you are using TA background for the first time, we recommend that you upload a few key events first.

# 3.1 Upload Events

It is recommended that you set the properties of the event and the conditions for sending information according to the previously combed doc. Event type is a stringtype that can only start with a letter and can contain numbers, letters and an underscore "_". It is up to 50 characters in length and is not sensitive to letter case.

Dictionary<string, object> properties = new Dictionary<string, object>()
    {
        {"KEY_DateTime", DateTime.Now.AddDays(1)},
        {"KEY_STRING", "B1"},
        {"KEY_BOOL", true},
        {"KEY_NUMBER", 50.65}
    };
ThinkingAnalyticsAPI.Track("TEST_EVENT", properties);
  • Event attributes are of type Dictionary < string, object >, where each element represents an attribute;
  • The event attribute Keyis the attribute name, which is of stringtype. It can only start with letters, including numbers, letters and underscore "_", with a maximum length of 50 characters, and is not sensitive to letter case;
  • Property values support five types: string, numeric, bool, DateTime, and Listtypes.

    Note: List type is supported in versions after v1.4.0, and its elements will be converted to string for storage.

When you call Track (), the SDK will take the current system time as the time when the event occurred. If you need to specify the event time, you can pass in DateTimetype parameters to set the event trigger time. Since the v1.3.0 version, the SDK supports uploading the time offset of the event according to the DataTimeKind(corresponding to the preset attribute #zone_offset), but if the incoming DateTime's Kindattribute is DataTimeKind. Unspecified, the time offset will not be reported:

DateTime dateTime = DateTime.Now.AddDays(-1);
ThinkingAnalyticsAPI.Track("TEST_EVENT", properties, dateTime);

Since v1.4.3, you can configure the default time zone for an SDK instance. If you configure a non-Local time zone, all event times will be aligned to that time zone, and the Kindproperty of the DateTimeyou pass in will be ignored.

Note: Although the trigger time can be set for the event, the receiving end will only receive data from the first 10 days to the last 3 days relative to the server time. Data exceeding the time limit will be regarded as abnormal data and the whole data cannot be stored.

# 3.2 Set Static Public Properties

For some important attributes, such as the player's zone suit and channel, these attributes need to be set in each event. At this time, you can set these attributes as public event attributes. The public event property refers to the property that each event will carry. You can call SetSuperPropertiesto set the public event property. We recommend that you set the public event property before sending the event.

Dictionary<string, object> superProperties = new Dictionary<string, object>()
    {
        {"SERVER", 0},
        {"CHANNEL", "A3"}
    };
ThinkingAnalyticsAPI.SetSuperProperties(superProperties);

The public event properties will be saved to the cache and need not be called every time the app is started. If a call to SetSuperPropertiesuploads a previously set public event property, the previous property is overwritten. If the public event property and the Keyof a property uploaded by Track ()duplicate, the property of the event overrides the public event property.

If you need to delete a public event property, you can call UnsetSuperProperty ()to clear one of the public event properties; if you want to empty all public event properties, you can call ClearSuperProperties ().

// Clear public property named CHANNEL
ThinkingAnalyticsAPI.UnsetSuperProperty("CHANNEL");

// Clear all public attributes
ThinkingAnalyticsAPI.ClearSuperProperties();

# 3.3 Set Dynamic Public Properties

If the value of the public property is not constant, you can do it by setting the dynamic public property. The dynamic public property is also added to all events, and the actual reported value is dynamically obtained when the event is reported.

To set dynamic public properties, you need to create a new dynamic public property class and implement the IDynamicSuperProperties interface, overwrite the public Dictionary < string, object > GetDynamicSuperProperties ()method, and the return value of this method is the dynamic public property that needs to be set. Then call SetDynamicSuperPropertiesto pass in the dynamic public property object, the sample is as follows:

using ThinkingAnalytics;

// Define the implementation of dynamic common attributes, for example, to set dynamic common attributes for UTC time
public class DynamicProp : IDynamicSuperProperties
{
    public Dictionary<string, object> GetDynamicSuperProperties()
    {
        return new Dictionary<string, object>() {
            {"KEY_UTCTime", DateTime.UtcNow}
        };
    }
}

ThinkingAnalyticsAPI.SetDynamicSuperProperties(new DynamicProp());

Note: If the event property has a duplicate name, the dynamic public property has a higher priority than the public event property and is less than the event property set in Track.

# 3.4 Record the Duration of the Event

If you need to record the duration of an event, you can call TimeEvent ()to start timing, configure the event type you want to time, and when you upload the event, you will automatically add #durationto your event attribute to indicate the duration of the recording, in seconds.

// Call TimeEvent to open for TIME_ Timing of EVENT events
ThinkingAnalyticsAPI.TimeEvent("TIME_EVENT");

// do some thing...

// Upload TIME_via Track When an EVENT event occurs, the #duration attribute is added to the attribute
ThinkingAnalyticsAPI.Track("TIME_EVENT");

# IV. User Attributes

TA platform currently supports the user feature setting interface for UserSet, UserSetOnce, UserAdd, UserUnset, UserDelete, UserAppend.

# 4.1 UserSet

For general user features, you can call the UserSetto set it. Attributes uploaded using this interface will overwrite the original attribute values. If the user feature does not exist before, the user feature will be created.

ThinkingAnalyticsAPI.UserSet(new Dictionary<string, object>()
    {
        {"USER_PROP_NUM", 0},
        {"USER_PROP_STRING", "A3"}
    });

Similar to event properties:

  • The user feature is a Dictionary < string, object >type, where each element represents an attribute;
  • User feature Keyis the attribute name, for the stringtype, the provisions can only start with a letter, including numbers, letters and underscore "_", the maximum length of 50 characters, not sensitive to letter case;
  • User feature values support four types: string, numeric class, bool, DateTime, and List.

    Note: List type is supported in versions after v1.4.0, and its elements will be converted to string for storage.

# 4.2 UserSetOnce

If the user feature you want to upload only needs to be set once, you can call UserSetOnceto set it. When the attribute already has a value before, this information will be ignored:

ThinkingAnalyticsAPI.UserSetOnce(new Dictionary<string, object>()
    {
        {"USER_PROP_NUM", -50},
        {"USER_PROP_STRING", "A3"}
    });

Note: The user feature type and restrictions set by UserSetOnce are consistent with UserSet.

# 4.3 UserAdd

When you want to upload a numeric attribute, you can call UserAddto accumulate the attribute. If the attribute has not been set, it will be assigned a value of 0and then evaluated. Negative values can be passed in, which is equivalent to subtraction operations.

ThinkingAnalyticsAPI.UserAdd(new Dictionary<string, object>()
    {
        {"USER_PROP_NUM", -100.9},
        {"USER_PROP_NUM2", 10.0}
    });

Note: The restrictions on attribute types and key values in UserAdd are consistent with UserSet, but Value only allows numeric type attributes to be reported.

# 4.4 UserUnset

If you need to reset a user attribute, you can call UserUnsetto clear the value of the user feature specified by the user. This interface supports passing in parameters of string or list type:

// Delete individual user attributes
ThinkingAnalyticsAPI.UserUnset("userPropertyName");

// Delete individual user attributes
List<string> listProps = new List<string>();
listProps.Add("aaa");
listProps.Add("bbb");
listProps.Add("ccc");

ThinkingAnalyticsAPI.UserUnset(listProps);

# 4.5 UserDelete

If you want to delete a user, you can call UserDeleteto delete the user. You will no longer be able to query the user features of the user, but the events generated by the user can still be queried.

ThinkingAnalyticsAPI.UserDelete();

# 4.6 UserAppend

Starting with v1.4.0, you can call UserAppendto append elements to a user feature of type List:

List<string> stringList = new List<string>();
stringList.Add("apple");
stringList.Add("ball");
stringList.Add("cat");

// Name property USER_ LIST adds 3 elements to its user attributes
ThinkingAnalyticsAPI.UserAppend(new Dictionary<string, object>
    {
        {"USER_LIST", stringList }
    });

# V. Automatic Acquisition Events

If the Auto Track option is checked when configuring the SDK, the SDK will automatically record:

  • ta_app_startThat is, the game launch event is triggered every time the user gains focus (that is, in the game)
  • ta_app_endThe game shutdown event is triggered when the game enters the Pausestate, and the #durationattribute will be attached to record the duration of the game (in seconds)

Starting from version 1.1.0, installation events can be collected through interface calls:

// Collect APP installation events
ThinkingAnalyticsAPI.TrackAppInstall();
  • ta_app_install, the game installation event, the installation event will only start when the user opens the APP for the first time after installation, the user upgrades the APP will not trigger, and the event will be triggered again after the user deletes and reinstates the APP.

# VI. Other Configuration Options

# 6.1 Get the Device ID

After the SDK is initialized, the device ID will be automatically generated and recorded in the local cache. For the same application/game, the device ID of a device is unchanged. You can call GetDeviceId ()to obtain the device ID:

ThinkingAnalyticsAPI.GetDeviceId();

// Use Device ID as Visitor ID
// ThinkingAnalyticsAPI.Identify(ThinkingAnalyticsAPI.GetDeviceId());

# 6.2 Delayed Reporting

If you check the Postpone Track option, it means that all report requests (including user feature settings and event tracking) will be cached until you actively call the following methods:

ThinkingAnalyticsAPI.StartTrack();

When this interface is called, the data will start to be reported. **For the data generated before the interface is called, when reporting, the user ID will be reset and public attributes will be added **. Therefore, setting the user ID and public attributes before calling StartTrack ()can be effective for all data, suitable for scenarios that need to **set guest ID and public attributes **:

//Set Visitor ID
ThinkingAnalyticsAPI.Identify(ThinkingAnalyticsAPI.GetDeviceId());

//Setting Common Properties
Dictionary<string, object> superProperties = new Dictionary<string, object>()
    {
        {"SERVER", 0},
        {"CHANNEL", "A3"}
    };
ThinkingAnalyticsAPI.SetSuperProperties(superProperties);

//Call Update Start Interface
ThinkingAnalyticsAPI.StartTrack();

# 6.3 Pause/stop Data Reporting

In version 2.1.0, the function of stopping SDK reporting data has been added. There are two types of interfaces to stop SDK reporting:

  1. Suspend SDK reporting (EnableTracking)

You may want to temporarily stop SDK data collection and reporting in some scenarios, such as the user is in a test environment, or the user logs in to a test account. At this time, you can call the following interfaces to temporarily stop SDK reporting.

You can call EnableTrackingthrough an instance (including the main instance and the light instance) and pass in falseto suspend the reporting of the SDK. The #distinct_id, #account_id, and public attributes that have been set by the instance will be retained; the data that has been collected but has not been successfully reported by the instance will continue to try to report; the subsequent instance cannot collect and report any new data, cannot set visitor ID, account ID, and public attributes, etc., but can read the public attributes and Device ID, guest ID, account ID and other information.

The stop state of the instance will be saved in the local cache until EnableTrackingis called and trueis passed in. The SDK instance will resume data collection and reporting. It should be noted that the light instance is not cached, so every time you open the APP, The paused state of the light instance will not be retained, and the reporting will be reopened.

// Pause reporting of default instances, cached data and information that has been set are not cleared
ThinkingAnalyticsAPI.EnableTracking(false);

// Restore reporting of default instances
ThinkingAnalyticsAPI.EnableTracking(true);
  1. Stop SDK reporting (OptOutTracking)

In some special situations, you may need to completely stop the functions of the SDK. For example, in areas where GDPR is applicable, users choose not to provide data collection permissions, you can call the following interface to completely turn off the functions of the SDK.

OptOutTrackingcan only be called through the primary instance, and the biggest difference with EnableTrackingis that it will empty the local cache of the instance, including the guest ID, account ID, public attributes, and unreported data queues of this instance. Then turn off the collection and reporting functions of this instance.

// Stop reporting default instances and empty local caches
ThinkingAnalyticsAPI.OptOutTracking();

If you want to delete the user's user data in the TA cluster while turning off the SDK function, you can call OptOutTrackingAndDeleteUser, which will report a piece of UserDeletedata before stopping the function of the SDK instance to delete the user's user data.

// Stop reporting the default instance and send user_ Del
ThinkingAnalyticsAPI.OptOutTrackingAndDeleteUser();

The stopped state of the instance will also be saved in the local cache until OptInTrackingis called, and subsequent reports can continue, but this is equivalent to a completely new instance

// Re-start reporting
ThinkingAnalyticsAPI.OptInTracking();

# 6.4 Creating Light Instances

You can create multiple instances under the same APP ID by light instances

// Create a light instance and return to the token of the light instance (Like APP ID)
string lightToken = ThinkingAnalyticsAPI.CreateLightInstance();

// Set Account ID for Light Instance
ThinkingAnalyticsAPI.Login("anotherAccount", lightToken);

// Report Events via Light Instance
ThinkingAnalyticsAPI.Track("TEST_EVENT", lightToken);

Note: The APP ID, reporting address and some settings of the child lightweight instance are consistent with the parent instance, but other information is not shared

# 6.5 SDK Operation Mode

Since v1.4.0, the SDK supports running in three modes:

  • NORMAL: Normal mode, data will be stored in the cache and reported according to a certain cache policy
  • DEBUG: Debug mode, data is reported one by one. When problems occur, users will be prompted with logs and exceptions
  • DEBUG_ONLY: Debug Only mode, only check the data, not into the library

    Note: DEBUG mode is only used for integration phase data validation and should not be used in production mode.

In order to prevent Debug mode from going live in the production environment, it is stipulated that only specified devices can turn on Debug mode. Debug mode can only be enabled on the client side, and the device ID is configured in the "Debug Data" section of the 'Event tracking management' page in the background of the TA.

The device ID can be obtained in three ways:

  • #device_id attribute in event data in TA platform
  • Client side log: The device DeviceId is printed after the SDK initialization is completed
  • Called through the instance interface: get device ID

# Release Note

# v1.4.4 2020/04/17

  • Fix double type formatting error in custom CultureInfo scenario

# v1.4.3 2020/03/19

  • Supports default time zone settings for data #time property
  • Update native SDK version

# v1.4.2 2020/02/21

  • Update iOS plugin to fix bugs introduced in older versions iOS systems

# v1.4.1 2020/02/14

  • Adapt to Unity 2019.3.1f1

# v1.4.0 2020/02/11

  • Property values support List/Array types
  • Add UserAppend interface
  • Support Debug mode data validation
  • Support to configure the receiving end address separately for each instance
  • Remove local data format validation

# v1.3.1 2019/12/25

  • Fix Android 4.3 Exit Timeout
  • Fix an error when iOS development environment is not included

# v1.2.0 2019/09/02

  • Support to turn off/on data reporting
  • Support pause/continue data reporting
  • Supports lightweight instances
  • Fix 2019.2.1f version setting network type failure
  • Fix timeEvent inaccuracy
  • Android/iOS SDK upgrade to 2.1.0

# v1.1.0 2019/08/09

  • Support for obtaining device ID
  • Support dynamic public attributes
  • Support installation event collection
  • Embedded Android SDK upgraded to 2.0.2
  • Embedded iOS SDK upgraded to 2.0.1
  • Support the report caching option, users can choose to actively call StartTrack ()to start reporting

# v1.0.0 2019/06/20

  • Supports settings for Visitor ID and User Account
  • Support event and user feature reporting
  • Supports automatic reporting of ta_app_startand ta_app_endevents
  • Support public property interface
  • Support timeEventinterface
  • Support multi-project reporting