Docs > Unity SDK

Unity SDK

In this integration guide we will take you through the most important steps of instrumenting your game with the GameAnalytics Unity SDK.

Known issue:
On Unity 2019.2 there is an issue with importing ‘Assets/GameAnalytics/Plugins/GameAnalytics.dll’ which makes the importing of the GameAnalytics Unity SDK package freeze and does not complete. A quick fix for this is to delete ‘Assets/GameAnalytics/Plugins/GameAnalytics.dll’. This of course means you will not be able to build for desktop platforms (Windows, Mac or Linux). We are sorry for the inconvenience and we trying to fix this issue as soon as possible.

Note: There is a fix now in v5.1.11

#

setup

Copy link to clipboard
#

Download and Installation

Copy link to clipboard

Important Announcement
From v3.11.0 and onwards you need to manually initialize the SDK by calling GameAnalytics.Initialize() from your own GameObject (with script execution order coming after GameAnalytics script’s order if your object is in the same scene as the GameAnalytics object as some code is called on Awake event which needs to be called before initializing the sdk).

Read more about it in the Initialization section here.

The Unity SDK supports Windows, Mac, Linux, WebGL, iOS, tvOS, UWP, Tizen, Universal Windows 8 and Android.

1. Download SDK

Download

2. Import SDK

Package (Unity) 

  • In the Unity editor go to Assets > Import Package > Custom Package.
  • Browse to the package location on your hard disk.
  • Leave all the files checked and click Import.

Check that the Unity environment has been already configured with the modules for the platforms you are targeting.

If you are targeting iOS, this is a good time to go to File > Build Settings > iOS and make sure the iOS module is loaded and you can create iOS builds.

Repository (Github).

Unzip the GameAnalytics files and copy them all into the Assets folder in your Unity project.

3. Verify Installation. 

Look in the Window menu in the Editor and there will be a GameAnalytics entry.

#

Sign Up and Login

Copy link to clipboard

1. Access Settings 

Through the toolbar menu select Window/GameAnalytics/Select Settings. A Settings gameobject will automatically be created if not located.

2. Account Creation 

If you have not already, you can register for a GameAnalytics accounts via our online form here or via the Settings menu in the Unity editor.

After you have signed up you will be asked to create a studio and a game. If your game is already published and on an app store you can search for it using the provided search field or else you can create it manually.

3. Login

    • Click the Login button in Settings and enter your credentials.
    • After login, you can select an existing studio/game by selecting your platform and then Add Platform. When selected the game key and the secret key will be automatically fetched and configured.

Don’t have any keys yet? Head over here and register your game at the GameAnalytics website!

You can then find your game’s keys within the game settings.

Game Keys

Find out more information about game keys

 

#

Initialization

Copy link to clipboard

You need to manually initialize the SDK by calling `GameAnalytics.Initialize()` from your own GameObject (with script execution order coming after GameAnalytics script’s order if your object is in the same scene as the GameAnalytics object as some code is called on Awake event which needs to be called before initializing the sdk).

What is the GameAnalytics GameObject?

To use GameAnalytics you need to add the GameAnalytics GameObject to your starting scene. It is `required` and used to handle initialization when the game is launched.

Create a GameAnalytics GameObject

Open the initial scene the game will load. Then select:
Window > GameAnalytics > Create GameAnalytics object

A GameAnalytics object will be placed in the scene you are currently on (remember to save the scene to keep the changes).

Make sure only one GameAnalytics object exists in your entire game. It will not be destroyed upon scene changes.

When to log events?

Unity provides the GameObject methods called awake and start.
First all GameObjects get the awake call. When every awake is done then all GameObjects get the start call.

The execution order for each is not fixed.

The GameAnalytics settings GameObject is initialized in the awake method, but other GameObjects could have had their awake call happen before this.

Therefore when submitting events from GameObjects in Unity it is recommended to do this after (or inside) the start method. This will ensure everything is ready.

If an event is submitted before initialization then the log will output something like this.

Warning/GameAnalytics: Could not add design event: Datastore not initialized

No events are actually being generated in the Editor. You need to build and run the game for the platform of your interest.

Read more about Unity execution order here.

#

Proguard (only Android)

Copy link to clipboard

If your app uses proguard add these rules to your proguard rules:

-keep class  com.gameanalytics.sdk { *; }
-keep class  com.gameanalytics.sdk.** { *; }
 
-keep class  com.gameanalytics.sdk.GAPlatform { *; }
-keep class  com.gameanalytics.sdk.GAPlatform.** { *; }
-keep class android.net.ConnectivityManager.** { *; }
#

event tracking

Copy link to clipboard

GameAnalytics supports 5 different types of events: Business, Resource, Progression, Error and Design.

To send an event, remember to include the namespace GameAnalyticsSDK:

using GameAnalyticsSDK;

If you are knew to GameAnalytics and our Events, please read our event guide here. You will get the most benefit of GameAnalytics when understanding what and how to track.

Event Types

Read our in-depth guide to understand what and how to track events

#

Business

Copy link to clipboard

Business Events (with validation)

Receipt validation in Unity is supported for the following stores.

  • App Store (iOS)
  • Google Play Store (Android)
// Android - Google Play
#if (UNITY_ANDROID)
GameAnalytics.NewBusinessEventGooglePlay (string currency, int amount, string itemType, string itemId, string cartType, string receipt, string signature)
#endif

// iOS - with receipt
#if (UNITY_IOS)
GameAnalytics.NewBusinessEventIOS (string currency, int amount, string itemType, string itemId, string cartType, string receipt)
#endif

// iOS - with autoFetchReceipt
#if (UNITY_IOS)
GameAnalytics.NewBusinessEventIOSAutoFetchReceipt (string currency, int amount, string itemType, string itemId, string cartType)
#endif
Field Type Description Example
currency string Currency code in ISO 4217 format. USD
amount integer Amount in cents. 99 is 0.99$
itemType string The type / category of the item. GoldPacks
itemId string Specific item bought. 1000GoldPack
cartType string The game location of the purchase.Max 10 unique values. EndOfLevel
iOS Fields Type Description
receipt base64 string The App Store receipt. Null allowed.Read about App Store receipt here.
Android Fields Type Description
receipt string INAPP_PURCHASE_DATA. Null allowed. Read about Android receipt here.
signature base64 string INAPP_DATA_SIGNATURE. Null allowed. Read about Android signature here.

Android Receipt Contents

{
    "orderId": "<order_id>",
    "packageName": "<package_name>",
    "productId": "<product_id>",
    "purchaseTime": 1484080095335,
    "purchaseState": 0,
    "purchaseToken": "<purchase_token>"
}

The receipt assigned to the Android business event method should not be base64 encoded. The GameAnalytics Android library will encode the receipt for you.

iOS with AutoFetchReceipt

The method NewBusinessEventIOSAutoFetchReceipt will attempt to locate the latest receipt in iOS native code and submit the event if found

Retrieving Receipts with Unity IAP service

The IStoreController object that you used to initialize the Unity IAP service contains all the products available for purchase declared by you as well as the receipts.

The receipts can be accessed as follows:

private IStoreController controller;
private IExtensionProvider extensions;

//..
public class Receipt {
 
	public string Store;
	public string TransactionID;
	public string Payload;
 
	public Receipt()
	{
		Store = TransactionID = Payload = "";
	}
 
	public Receipt(string store, string transactionID, string payload)
	{
		Store = store;
		TransactionID = transactionID;
		Payload = payload;
	}
}
 
public class PayloadAndroid
{
    public string json;
    public string signature;
 
    public PayloadAndroid()
    {
        json = signature = "";
    }
 
    public PayloadAndroid(string _json, string _signature)
    {
        json = _json;
        signature = _signature;
    }
}

//... 
public PurchaseProcessingResult ProcessPurchase (PurchaseEventArgs args)
{
if (String.Equals (args.purchasedProduct.definition.id, kProductIDConsumable, StringComparison.Ordinal)) {
    //...
    		var product = m_StoreController.products.WithID(kProductIDConsumable);
			string receipt = product.receipt;
			string currency = product.metadata.isoCurrencyCode;
			int amount = decimal.ToInt32 (product.metadata.localizedPrice * 100);
#if UNITY_ANDROID
            Receipt receiptAndroid = JsonUtility.FromJson<Receipt>(receipt);
            PayloadAndroid receiptPayload = JsonUtility.FromJson<PayloadAndroid>(receiptAndroid.Payload);
            GameAnalytics.NewBusinessEventGooglePlay(currency, amount, "my_item_type", kProductIDConsumable, "my_cart_type", receiptPayload.json, receiptPayload.signature);
#endif
#if UNITY_IPHONE
			Receipt receiptiOS = JsonUtility.FromJson<Receipt> (receipt);
			string receiptPayload = receiptiOS.Payload;
			GameAnalytics.NewBusinessEventIOS (currency, amount, "my_item_type", kProductIDConsumable, "my_cart_type", receiptPayload);
#endif
}

On iOS you need to send the entire payload while for Android GameAnalytics should receive only the contents of the json field inside the payload. Information about these can be found in the Unity documentation about the receipts.

For parsing the receipt JSON and getting the data listed under the json field we recommend a JSON parser such as JSON Object.

We do not support purchase validation for any of the other platforms listed by Unity IAP (Mac App store or Windows store).

#

Resource

Copy link to clipboard

To add a resource event call the following function:

GameAnalytics.NewResourceEvent (GA_Resource.GAResourceFlowType flowType, string currency, float amount, string itemType, string itemId)
Field Type Required Description
flowType enum yes Add (source) or subtract (sink) resource.
currency string yes
One of the available currencies set in GA_Settings (Setup tab).This string can only contain [A-Za-z] characters.
amount float yes Amount sourced or sunk.
itemType string yes
One of the available item types set in GA_Settings (Setup tab).
itemId string yes Item id (string max length=32)

Be careful to not call the resource event too often! In a game where the user collect coins fairly fast you should not call a Source event on each pickup.

Instead you should count the coins and send a single Source event when the user either completes or fails the level.

Here are some examples and best practices for structuring the events:

GameAnalytics.NewResourceEvent(GA_Resource.GAResourceFlowType.GAResourceFlowTypeSource, “Gems”, 400, “IAP”, “Coins400”);

GameAnalytics.NewResourceEvent(GA_Resource.GAResourceFlowType.GAResourceFlowTypeSink, “Gems”, 400, “Weapons”, “SwordOfFire”);

GameAnalytics.NewResourceEvent(GA_Resource.GAResourceFlowType.GAResourceFlowTypeSink, “Gems”, 100, “Boosters”, “BeamBooster5Pack”);

GameAnalytics.NewResourceEvent(GA_Resource.GAResourceFlowType.GAResourceFlowTypeSource, “BeamBooster”, 5, “Gems”, “BeamBooster5Pack”);

GameAnalytics.NewResourceEvent(GA_Resource.GAResourceFlowType.GAResourceFlowTypeSink, “BeamBooster”, 3, “Gameplay”, “BeamBooster5Pack”);
#

Progression

Copy link to clipboard

To add a progression event call the following function:

// Using 1 progression part (01) and no score
GameAnalytics.NewProgressionEvent(GA_Progression.GAProgressionStatus progressionStatus, string progression01)

// Using 1 progression part (01) and score
GameAnalytics.NewProgressionEvent(GA_Progression.GAProgressionStatus progressionStatus, string progression01, int score)

// Using 2 progression parts (01+02) and no score
GameAnalytics.NewProgressionEvent(GA_Progression.GAProgressionStatus progressionStatus, string progression01, string progression02)

// Using 2 progression parts (01+02) and score
GameAnalytics.NewProgressionEvent(GA_Progression.GAProgressionStatus progressionStatus, string progression01, string progression02, int score)

// Using 3 progression parts (01+02+03) and no score
GameAnalytics.NewProgressionEvent(GA_Progression.GAProgressionStatus progressionStatus, string progression01, string progression02, string progression03, int score)

// Using 3 progression parts (01+02+03) and score
GameAnalytics.NewProgressionEvent(GA_Progression.GAProgressionStatus progressionStatus, string progression01, string progression02, string progression03, int score)
Field Type Required Description
progressionStatus enum yes Status of added progression (start, complete, fail).
progression01 string yes 1st progression (e.g. world01).
progression02 string no 2nd progression (e.g. level01).
progression03 string no 3rd progression (e.g. phase01).
score int no The player’s score.

If you do not need progression02 or progression03 do not make any references to these parameters when calling the method. Below you can learn from an example of progression event that uses only progression01 and progression02:

GameAnalytics.NewProgressionEvent (GAProgressionStatus.Start, "World1");
GameAnalytics.NewProgressionEvent (GAProgressionStatus.Complete, "World1", score);
GameAnalytics.NewProgressionEvent (GAProgressionStatus.Start, "World1", "Level1");
GameAnalytics.NewProgressionEvent (GAProgressionStatus.Complete, "World1", "Level1", score);
GameAnalytics.NewProgressionEvent (GAProgressionStatus.Start, "World1", "Level1", "Phase1");
GameAnalytics.NewProgressionEvent (GAProgressionStatus.Complete, "World1", "Level1", "Phase1", score);
#

Error

Copy link to clipboard

To add a custom error event call the following function:

GameAnalytics.NewErrorEvent (GAErrorSeverity severity, string message)
Field Type Required Description
severity enum yes Severity of error (critical, debug, error, info, warning).
message string yes Error message (Optional, can be null).
#

Design

Copy link to clipboard

To add a design event call the following function:

GameAnalytics.NewDesignEvent (string eventName, float eventValue)
Field Type Required Description
eventName string yes The event string can have 1 to 5 parts. The parts are separated by ‘:’ with a max length of 64 each. e.g. “world1:kill:robot:laser”. The parts can be written only with a-zA-Z0-9 characters.
eventValue float no Number value of event.

 

#

unity settings

Copy link to clipboard
#

Game Settings

Copy link to clipboard

Game Keys

  • To use GameAnalytics you need a game key and a game secret for each platform you are using (iOS / Android).
  • The game key is a unique identifier for your game while the secret key is used to protect event data from being tampered with as it travels to the GameAnalytics servers.

Build Version

  • The build is used to specify the current version of your game. Specify it using a string.
    Recommended using a 3 digit version like [major].[minor].[patch]
  • The build version should be used for changing production builds of the game. We recommend creating a separate game when implementing or testing the SDK.

Custom Dimensions

  • During gameplay, it is possible to set values for 3 different custom dimensions.
  • For each custom dimension, it is needed specify a whitelist.
  • You cannot set a custom dimension value unless it is specified here first. For more information about custom dimensions go here.

Resource types

  • When submitting resource events you specify a resource currency and resource item type. It is needed to specify a whitelist for each of these.
  • You cannot submit a resource event using other values than specified here.
  • Each resource currency string should only contain [A-Za-z] characters.
#

Player Settings

Copy link to clipboard
  • It is imperative to avoid including non-alpha-numerical characters in the company name in PlayerSettings.
  • This name is included when creating temporary local files and as a result a character like ; would break the path to these files.
#

Advanced Settings

Copy link to clipboard

Custom ID

  • The SDK will automatically generate a user id and this is perfectly fine for almost all cases.
  • Sometimes it is useful to supply this user_id manually – for example, if you download raw data for processing and need to match your internal user id (could be a database index on your user table) to the data collected through GameAnalytics.
  • Note that if you introduce this into a game that is already deployed (using the automatic id) it will start counting existing users as new users and your metrics will be affected. Use this from the start of the app lifetime.

Use the following piece of code to set the custom user id:

 GameAnalytics.SetCustomId("user1234567879");

When using custom id you need to remember GameAnalytics will first be fully initialized when you have set the custom id. No events can be sent before GameAnalytics is fully initialized.

Manual Session Handling

If enabled manual session handling will be enabled automatically just before initialization. To manual enable or disable session handling later on call this:

 GameAnalytics.SetEnabledManualSessionHandling(true);

Read more about sessions here.

Submit Errors

  • Enable this to catch error and exception messages within Unity when the game is running and submit them to GameAnalytics.
  • This is useful for discovering unforeseen issues after the game has been launched. It will submit an error event using the type error, warning or critical.

After a game has been launched it will only send a maximum of 10 error events automatically. Some games can generate a lot of exceptions and this cap will prevent degraded performance and unintended bandwidth usage.

Submit Average FPS

  • Enable this to calculate and submit average FPS automatically.
  • The frame rendering will be monitored during an interval of 20 seconds. Then a design event called GA:AverageFPS is submitted with the average FPS as a value.

Submit Critical FPS

The average FPS is useful for general performance overview, but it will not detect critical FPS drops. These drops are often more noticeable by players versus a low (but steady) average FPS.

Enable the critical fps detection to submit an event when sudden drops in FPS are detected. This is done by calculating average FPS over the last second. If this should drop below 10 it will register this occurrence internally. After 20 seconds it will select the lowest critical FPS registered (if any) and submit a design event called GA:CriticalFPS with the critical average FPS.

#

Debug Settings

Copy link to clipboard

The SDK is designed to be as silent as possible and use few resources. You will therefore not get much information by default when actions or errors occur.

The SDK consists of Unity code (C# wrapper) that call code inside some native libraries (iOS / Android). When playing in the editor the native code is not compiled/used. To get the detailed console output generated from the native code it is needed to compile/launch the game in native.

Info Log Editor

When playing in the editor you will get output whenever an event is added from Unity code. It will not submit (from native code) as this part of the SDK is not compiled when playing in the editor. The events are not validated yet and you will therefore not get any errors related to validation or authentication.

Use editor debugging when implementing events into your game to verify events are called at the correct place/time and with the intended data.

Info Log Build

The info log will output basic information about what is happening when your game is built for native.

Verbose Log Build

The verbose log will output the event JSON data that is being sent to the GameAnalytics servers when your game is built for native.

#

Unity 4.6

Copy link to clipboard

Specific settings are required for Unity 4.6.x when targeting mobile platforms, as described below

You need to tell the GameAnalytics SDK that you are targeting mobile platforms when using the package for Unity 4.6.x. Go to Window → GameAnalytics → Exclude GA Mono DLLs. When switching to targeting other platforms than mobile simply select the Include GA Mono DLLs option.

 

 

#

platform builds

Copy link to clipboard
#

iOS

Copy link to clipboard

Build script – Unity 5 / Xcode7

  • A Unity build-script (GameAnalytics → Editor → GA_PostprocessBuild.cs) will configure the generated Xcode project automatically during the build phase.
  • This is only supported in Unity 5 (supporting the post-build) and Xcode7+ (using the .tbd libraries).

Build script – Unity 4.6

  • The XCode API is only directly included in Unity 5 but the XCode API is actually packaged with Unity 4.6 you just need to copy UnityEditor.iOS.Extensions.Xcode.dll into the plugins folder.
  • Under Mac OS X is found at /Applications/Unity/Unity.app/Contents/PlaybackEngines/iossupport and under Windows, it is found at C:Program FilesUnityEditorDataPlaybackEnginesiossupport (both assuming you installed Unity at the default location).
  • The last thing you need to do is open the GA_PostprocessBuild.cs file (located under GameAnalytics/Editor) and comment out the first line with…
#if !UNITY_4_6

and the last line with

#endif

Manual Configuration

  • If you are not using Unity 5 (or the process above) then you need to configure build settings manually.
  • In Xcode go to the configuration section called Build Phases and locate the Link Binary With Libraries. Add the following for Xcode7 (using .tbd libraries).
    • AdSupport.framework
    • SystemConfiguration.framework (included by Unity by default)
    • libsqlite3.tbd
    • libz.tbd
    • libGameAnalytics.a

A Unity game will automatically include additional libraries that are not listed above.

Are you deploying testflight builds?
Please note that every launch of a testflight game will generate a new user. This is due to how testflight is simulating certain device identifiers. A testflight game will register the same user as a “New User” each time the game is launched. Once it is deployed to the app store (or run locally on an actual device) it will track user metrics correctly.

#

Android

Copy link to clipboard

Merging AndroidManifest

  • If you are using other plugins which have their own AndroidManifest.xml file then you may get build errors.
  • You can delete the AndroidManifest that comes with the GameAnalytics SDK, as long as you include the following in the AndroidManifest you are using:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

and:

<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

Storage Permissions

  • READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions are optional.
  • The SDK will use context.getExternalCacheDir() (if it exists) to store its internal database, as the database can reach up to 10MB if the user keeps being offline for longer periods of time while playing to still be able to send the events when the user is back online.

 

Play Services Resolver

From version 5.0.5 we have added “Play Services Resolver” to resolve Android library dependencies. It should automatically resolve the dependencies but if any issues occur it can also be done manually like shown on the image below:

Conflicting Google Play Services library

  • If you are using other plugins which include their own Google Play Services library then you may get build errors.
  • A popular example of this is if you’re including the Chartboost SDK. In this case, it should work to delete the “google-play-services_lib” folder which was added when importing the Charboost SDK package.
  • Another option is to delete the following two files that come with the GameAnalytics SDK:
    • play-services-ads-9.4.0.arr
    • play-services-basement-9.4.0.arr

This approach should work with any plugin that includes the Google Play Services library.

Exclude Google Play Services libraries

  • To exclude Google Play Services libraries (only relevant for markets where Google Play is not allowed for example in China) to you need to click on the following menu item:

Window -> GameAnalytics -> Exclude Google Play Services libraries (Android only)

  • To include the libraries again you can click on the following menu item:

Window -> GameAnalytics -> Include Google Play Services libraries (Android only)

#

UWP

Copy link to clipboard

Remember to add InternetClient capability under Player Settings in Unity.

#

Windows Universal 8

Copy link to clipboard

Remember to add the following to your package manifest file:

<Dependencies> 
    <PackageDependency Name="Microsoft.VCLibs.110.00" MinVersion="11.0.0.0" />
    <PackageDependency Name="Microsoft.VCLibs.140.00" MinVersion="14.0.0.0" /> 
</Dependencies>
#

Tizen

Copy link to clipboard

Add the following capabilities under Tizen settings in Unity (under Publishing settings):

  • NetworkGet
  • Internet

#

command center

Copy link to clipboard

#

Configs

Copy link to clipboard

Product Update – Remote Configs

We are excited to announce the upcoming release of Remote Configs – our new tool that will replace Configs.

Remote Configs will be released in October 2019 with a new user interface and updated SDKs.

You can continue to use the current version of Configs. We will soon be sharing more information and our migration guide.

If you have any questions, please don’t hesitate to reach out.

Register to events for whenever the Config (CommandCenter) is updated with new values:

private static void MyOnCommandCenterUpdateFunction()
{
    // add your code here
}

GameAnlytics.OnCommandCenterUpdatedEvent += MyOnCommandCenterUpdateFunction;

To manual check if Configs is ready (has been populated with values) you can call this:

if(GameAnalytics.IsCommandCenterReady())
{
    // the command center is ready, add your code here
}

To get values out of a populated Config use the following methods:

// Without custom default value (using normal default value)
string value = GameAnalytics.GetCommandCenterValueAsString("key");
// With custom default value
string valueWithCustomDefaultValue = GameAnalytics.GetCommandCenterValueAsString("key", "myDefaultValue");

If the specified key is not found in the Config it will return the default value either “normal” or “custom” default value.

#

additional calls

Copy link to clipboard

#

Enable/disable Event Submission

Copy link to clipboard

If you for GDPR purposes need to disable event submission you can call the following:

GameAnalytics.setEnabledEventSubmission(false);

By default event submission is of course enabled. You will still receive configs if you have set any for your game even after disabling event submission.

#

Set Custom Dimension

Copy link to clipboard

Read an overview of custom dimensions here.

  • To add custom dimensions to your events you will first have to create a list of all the allowed values.
  • You can do this in Settings under the Setup tab. Any value which is not defined will be ignored.

To set a custom dimension call one of the functions below.

Custom Dimension 1:

GameAnalytics.SetCustomDimension01 (string customDimension)

Custom Dimension 2:

GameAnalytics.SetCustomDimension02 (string customDimension)

Custom Dimension 3:

GameAnalytics.SetCustomDimension03 (string customDimension)
Field Type Required Description
customDimension string yes One of the available dimension values set in Settings (Setup tab). Will persist cross session. Set to null to remove again.
#

Set Facebook ID

Copy link to clipboard

If your game has Facebook integration you can submit the Facebook Id to GameAnalytics. You will then be able to get additional information about the types of players which play your game.

To set the Facebook Id call the following function:

GameAnalytics.SetFacebookId (string facebookId)
Field Type Required Description
facebookId string yes Facebook id of the player.
#

Set Gender

Copy link to clipboard

If your game has information about the player’s gender you can submit this to GameAnalytics. You will then be able to get additional information about the types of players which play your game.

To set the gender call the following function:

GameAnalytics.SetGender (GA_Setup.GAGender gender)
Field Type Required Description
gender string yes Gender of the player.
#

Set Birth Year

Copy link to clipboard

If your game has information about the player’s birth year you can submit this to GameAnalytics. You will then be able to get additional information about the types of players which play your game.

To set the birth year call the following function:

GameAnalytics.SetBirthYear (int birthYear)
Field Type Required Description
birthYear int yes Birth year of the player.
#

extras

Copy link to clipboard
#

PlayMaker

Copy link to clipboard

GameAnalytics is set up to work with PlayMaker to make it as easy as possible for you to send events using the visual PlayMaker scripting tools.

Activating the SDK for PlayMaker

You need to tell our SDK that it will be used with PlayMaker. To do so you need to toggle the SDK scripts by clicking Window>GameAnalytics>PlayMaker>Toggle Scripts.

Make sure at this stage PlayMaker is already added to Unity.

Using the SDK with PlayMaker

At this stage a new category for Actions named GameAnalytics should pop-up in the PlayMaker Actions list used for when adding an action to a state.

When using GameAnalytics actions you may notice that some of the parameters are mandatory while others can be set to none. Follow closely our documentation about each event type (Business, Design, Progression, Resource and Error) before using the actions.

In order to better understand how to use GameAnalytics please read our guidelines about the implementation process and how the tool reads custom events.

#

how does it work

Copy link to clipboard
#

Session Handling

Copy link to clipboard

By default the SDK will handle session start/end automatically, but it is also possible to manually control this yourself.

Be aware that the initialization will always automatically start the first session even with manual session handling.

Automatic Session Handling

The automatic session handling will track the focused time the user is spending in your game – from game launch to the user leaving the game.

session start
On Android a new session will start once the game is launched or when the app is resuming if there is no current session.

session end
A session will end once the game is going to home-screen (or is not visible anymore).

It will end the session at once if the application received the onStop event from the game activity. It can also end the session if onPause event was received and 90 seconds have passed (sometimes only the onPause will trigger even though the user left the app).

Manual Session Handling

The automatic session handling only works if the game is contained in one activity.

It will then handle session end and start based on the events on that single activity. This behavior is common (having one activity) but some games define multiple activities and this automatic session handling will not work in an optimal way.

If your game does have multiple activities (or you just want to be in control when to start and end sessions) you can enable/disable manual session handling by calling this at any given time:

GameAnalytics.setEnabledManualSessionHandling(true);

You will then need to call endSession and startSession at the appropriate times.

With manual session handling it is recommended to also call endSession when the game activity event onStop is fired. This will ensure a correct session close when users click the home or on/off button.

endSession()

GameAnalytics.endSession();

This will end a session if:

  • manual session handling is enabled
  • a session is active
  • SDK is initialized (initialize will start a session automatically)

startSession()

GameAnalytics.startSession();

This will start a new session if:

  • manual session handling is enabled
  • SDK is initialized (initialize will start a session automatically)

If a current session is active then it will end the current session and start a new one.

Behind the scenes

This is what happens when the session is starting or ending.

Session start

  1. Generate new session.
  2. Add a session start event (a “user” event).
  3. Start the periodic activation of submitting queued events.
  4. Next event submits will fix potential missing session_end from earlier sessions.

Session end

  1. Stop the periodic activation of submitting queued events.
  2. Add a session_end event.
  3. Submit queued events.
#

Example Script

Copy link to clipboard

Download script ↓

using UnityEngine;
using System.Collections;
using GameAnalyticsSDK;

public class EventTests : MonoBehaviour
{
	void OnGUI ()
	{
		if (GUI.Button (new Rect (10, 10, 200, 40), "Test Design Event")) {
			//Example of hierarchy with 2 levels. The event string can have 1 to 5 parts. The parts are separated by ‘:’ with a max length of 64 each.
			//拥有两层的层级结构示例。事件字符串可以包含1-5个部分,每个部分之间用“:”分隔开,最大长度为64。
			//The amount of possible unique events are count(part1)*count(part2)*...*count(part5).
			//唯一事件的数量可能为:part1的个数 * part2的个数 *...* part5的个数

			//Thus for the example below the maximum unique event count that can be reached is  count(armoryType) * count(itemRarity) * count(itemType)
			//针对下面的示例,唯一事件数量的最大值可能为:armoryType的个数 * itemRarity的个数 * itemType的个数
			
			//An instrumentation should not generate more than 50000 UNIQUE events!
			//Instrumentation不应该产生超过50000个唯一事件!
			string armoryType = "Weapons";
			string itemRarity = "Legendary";
			string itemType = "Sword";

			string event_id = armoryType + ":" + itemRarity + ":" + itemType;
			float event_value = 7.5f;
			GameAnalytics.NewDesignEvent (event_id, event_value);

			#if(!UNITY_EDITOR)
			Debug.Log("Design event added:" + event_id + " value:" + event_value);
			#endif
		}

		//It is mandatory to add receipt information to business events for games published on the App Store or on the Google Play store
		//对于在App Store和Google Play store上发行的游戏,将收据信息添加到商业事件(Business event)上是非常必要的。
		//in order to view accurate monetization metrics in the default dashboards.
		//以便在数据报表中查看准确的游戏收益指标。
		if (GUI.Button (new Rect (10, 60, 200, 40), "Test iOS/tvOS Business Event")) {
#if ((UNITY_IOS || UNITY_TVOS) && !UNITY_EDITOR)

			string iosReceiptPayloadExample = "MIIp1AYJKoZIhvcN........Bx7nN/k74=";
			GameAnalytics.NewBusinessEventIOS ("USD", 99, "TestItem", "1235672", "_myCartType", iosReceiptPayloadExample);

#elif (UNITY_ANDROID && !UNITY_EDITOR)

			//The SDK will encode the receipt in the native GameAnalytics native Library
			//SDK将在GameAnalytics本地库中对收据进行编码。
			string receiptGoogleExample = "{"orderId": "<order_id>", "packageName": "<package_name>", "productId": "<product_id>", "purchaseTime": 1484080095335, "purchaseState": 0, "purchaseToken": "<purchase_token>"}";
			GameAnalytics.NewBusinessEventGooglePlay("USD", 99, "TestItem", "1235672", "Store", receiptGoogleExample, "+transaction signature (already base64 encoded from Google.)+");

#else   //for any other supported platform: Windows, Mac, Linux, WebGL, UWP, Tizen and Universal Windows 8
	//我们支持的其他平台有:Windows,Mac,Linux,WebGL,UWP,Tizen和Universal Windows 8
			GameAnalytics.NewBusinessEvent ("USD", 99, "TestPurchase", "ItemId1235672", "_cartType");

#endif
			Debug.Log("Test business event added to queue."); 
//The business event will be marked as invalid unless real or sandbox transactions occur for iOS or Android.
//除非在iOS或Android上发生真实或沙盒交互,否则该business event将被标记为无效。
		}

		if (GUI.Button (new Rect (10, 110, 200, 40), "Add Error Event")) {
			try {
				throw new System.Exception ("GA Test Exception");
			} catch (System.Exception ex) {
				GameAnalytics.NewErrorEvent (GAErrorSeverity.Info, ex.ToString ());
				Debug.Log ("Error event added: " + ex.ToString ());
			}
		}

		if (GUI.Button(new Rect(10, 160, 200, 40), "Test Start Progression Event"))
		{
			string progression_01 = "World_01";
			string progression_02 = "Stage_01";
			string progression_03 = "SavingPrincess";

			//Event count can be increased by count(progression_01)*count(progression_02)*count(progression_03);
			//事件数量可能增加个数为:progression_01的个数 * progression_02的个数 * progression_03的个数;

			GameAnalytics.NewProgressionEvent(GAProgressionStatus.Start, progression_01, progression_02, progression_03);

#if(!UNITY_EDITOR)
			Debug.Log("Progression event added: " + "Start:" + progression_01 + ":" + progression_02 + ":" + progression_03);
#endif
		}

		if (GUI.Button(new Rect(10, 210, 200, 40), "Test Sink Resource Event"))
		{
			//Resouce currencies and itemTypes must be declared in the Settings GameAnalytics object under Assets/Resources/GameAnalytics
            		//资源货币(currency)和itemType必须在Assets/Resources/GameAnalytics下的Settings GameAnalytics object中声明。
			string currency = "silver";
			float amountSpent = 1000f;
			string itemType = "Shop";
			string itemID = "Minigun";

			GameAnalytics.NewResourceEvent (GAResourceFlowType.Sink, currency, amountSpent, itemType, itemID);
#if(!UNITY_EDITOR)
			Debug.Log("Resource event added: " + "Sink:" + "currency=" + currency + "; amount=" + amountSpent + "; itemType=" + itemType + "itemID=" + itemID);
#endif

		}

		//All custom dimensions used in code must be declared in the Settings GameAnalytics object under Assets/Resources/GameAnalytics
		//代码中使用的所有自定义维度必须在Assets/Resources/GameAnalytics下的Settings GameAnalytics object中声明。

		if (GUI.Button(new Rect(10, 260, 200, 40), "Custom dimension 1"))
		{
			GameAnalytics.SetCustomDimension01("Facebook");
		}

		if (GUI.Button(new Rect(10, 310, 200, 40), "Custom dimension 2"))
		{
			GameAnalytics.SetCustomDimension02("Horde");
		}

		if (GUI.Button(new Rect(10, 360, 200, 40), "Custom dimension 3"))
		{
			GameAnalytics.SetCustomDimension03("Ninja");
		}

		if (GUI.Button(new Rect(10, 410, 200, 40), "Set Facebook ID"))
		{
			GameAnalytics.SetFacebookId("myFacebookID123");
		}

		//This information can be collected but can only be examined by looking into the raw events data.
		//我们可以收集这些信息,但是只能通过查看原始事件数据来检查。
		if (GUI.Button(new Rect(10, 460, 200, 40), "Set Gender"))
		{
			GameAnalytics.SetGender(GAGender.male);
		}

		//This information can be collected but can only be examined by looking into the raw events data.
		//我们可以收集这些信息,但是只能通过查看原始事件数据来检查。
		if (GUI.Button(new Rect(10, 510, 200, 40), "Set Birth year"))
		{
			GameAnalytics.SetBirthYear(1984);
		}

		//Custom IDs should be used only if there is a need to do so. By default, GameAnalytics assigns and manages IDs to each unique user.
		//只有在有特殊需求时才使用自定义ID。默认情况下,GameAnalytics为每一个用户分配并管理他们的用户ID。
		//If 'Use custom ID' is enable in Settings then GameAnalytics will not start tracking any form of events until 'SetCustomId' is called.
		//如果在设置中开启“使用自定义ID”,接下来GameAnalytics将不会开始追踪任何形式的事件,直到调用“SetCustomID”。
		if (GameAnalyticsSDK.State.GAState.IsCustomIDEnabled ()) {
			if (GUI.Button (new Rect (10, 560, 200, 40), "Custom ID")) {
				GameAnalytics.SetCustomId ("my_custom_id");
			}
		}

		//Manual session should be used only if there is a need to do so. By default, GameAnalytics starts and ends sessions without any additional efforts required by the developer
		//只有在有特殊需求时才手动调用开始或结束会话。默认情况下,GameAnalytics追踪会话不需要开发者做任何额外的工作。

		if (GameAnalyticsSDK.State.GAState.IsManualSessionHandlingEnabled ()) {
			if (GUI.Button (new Rect (10, 610, 200, 40), "Start session")) {
				GameAnalytics.StartSession ();
			}
		}

		if (GameAnalyticsSDK.State.GAState.IsManualSessionHandlingEnabled ()) {
			if (GUI.Button (new Rect (10, 660, 200, 40), "End session")) {
				GameAnalytics.EndSession ();
			}
		}
	}
}

 

Contact support

We’ll get back to you ASAP.

Report a bug

Let us know more details.