Unity SDK

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

SETUP

Download and Installation

GameAnalytics Unity SDK is available either as a Unity package or directly from the Github repository.

Github Repository

?
The Unity package importer can only add & update files when importing. Deprecated files from earlier version might still remain.

If you experience any issues when updating exiting SDK then try to perform a clean import. Do this by deleting the old version of the package files from your project before importing.

ℹ️
At this stage you should make sure 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 Build Settings > iOS and make sure the iOS module is loaded and you can create iOS builds.

Unity package download

Download the latest package for Unity 5 directly from our servers.

Download the latest package for Unity 4.6.x directly from our servers.

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.

Repository download

You can also download all the files directly from the repository.

Github Repository

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

Verify installation

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


Unity might need a few seconds to process the new files before the menu show up.

iOS and tvOS Fix

The Unity SDK supports both iOS and tvOS. However, sometimes Unity does not set the correct platform when including the tvOS files. This can result in the following error when building for both iOS and tvOS.

This is easily fixed, however. In your project file hierarchy navigate to /Plugins/tvOS/ and select each file. In the inspector window view the list of the platforms that this file will be included in. Select only tvOS for these files.

Sign up and Login

Through the toolbar menu select Window/GameAnalytics/Select Settings.
A Settings gameobject will automatically be created if not located. 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.

It’s possible to sign up and login in the Unity editor.

Sign up

To signup in the editor click the Sign up button in the Settings.
During this process, an account will be created with a studio containing one game.
You will be automatically logged in afterward.

After you have signed up you will be asked to create 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.

Login

To login click the Login button in Settings and enter your credentials. After login, you can select a studio/game/platform from dropdown elements. When selected the game key and the secret key will be automatically fetched and configured.

ℹ️
Once a game has been created it can take a few minutes before the GameAnalytics servers will accept events for that game. You can of course always create games manually in our tool and locate the keys in the game settings.

Settings


To access settings you need to locate and select the Settings GameObject. Settings can be found under Resources/GameAnalytics or by going to the menu Window → GameAnalytics → Select Settings.

Settings for Unity 4.6.x when targeting mobile platforms

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.

Account

On the account tab, you can sign up or log in to a GameAnalytics account directly in the editor.

ℹ️
Read here about signup and login through the editor.

Setup

In the Setup tab, you specify the game keys and the build version.
Additionally, you can configure available custom dimensions and resource types.

Game Key + Secret Key

For each platform, you need to configure a set of game keys.

ℹ️
game key
is a unique identifier for your game.

secret key is used to protect event data from being tampered with as it travels to the GameAnalytics servers.

Build

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 Currency and Item 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.

Advanced

Advanced Settings

Use 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:

ℹ️
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.

Use 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:

Read more about sessions here including manual session handling.

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

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.

GameAnalytics Object

What is the GameAnalytics object?

The GameAnalytics object is a Unity game object that should be placed inside your initial scene. It is required and used to handle initialization when the game is launched.

ℹ️
Read more here about all the settings available for the SDK.

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 initializing 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 initialize then the log will output something like this.

⚠️
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.

PLATFORM BUILDS

iOS Build

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 Files\Unity\Editor\Data\PlaybackEngines\iossupport (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…

and the last line with

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 Build

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:

and:

Storage permissions

READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions are optional. If the user’s device has Android API level 19 (KitKat) or above, the SDK will try 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. If the device is less than Android API level 19 (Kitkat) but if READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions have been added the SDK will also try to use context.getExternalCacheDir(). If the none of the previously mentioned conditions have been met, then context.getCacheDir() will be used for storage of the internal database.

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 Build

Remember to add InternetClient capability under Player Settings in Unity.

Windows Universal 8 Build

Remember to add the following to your package manifest file:

Tizen Build

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

  • NetworkGet
  • Internet

ADDING EVENTS

About

About Events

An event should be added when an important action is happening in your game. Some very frequent events should be aggregated locally (sum) during a level and then submitted in one event (like coin pickups).

GameAnalytics cover general areas.

  • monetization (business)
  • virtual economy (resource)
  • progression

But also provide more flexibility in the design event specifying custom event ids.

Games are different! Therefore the events that make sense to track will be different.

⚠️
Event id’s are strings separated by colons defining an event hierarchy – like kill:robot:large.

It is important to not generate an excessive amount of unique nodes possible in the event hierarchy tree.

A bad implementation example. [level_name]:[weapon_used]:[damage_done]

level_name could be 100 values, weapon_used could be 300 values and damage_done could be 1-5000 perhaps. This will generate an event hierarchy with: 100 * 300 * 5000 = 150M possible nodes. This is far too many. Also the damage should be put as a value and not in the event string.

The processing will perhaps be blocked for a game doing this and cause other problems when browsing our tool. The maximum amount of unique nodes generated should be around 10k.

ℹ️
Please read our event guide here. You will get the most benefit of GameAnalytics when understanding what and how to track.

Business

Business Events (with validation)

Business events are used to track in-app purchases with real money.

ℹ️
Mobile games can be hacked and distributed illegally.
Hacking an app will often involve faking/simulating all purchase requests. This will result in several Business events being sent to GameAnalytics for transactions that never occurred. GameAnalytics provide the option of receipt validation for each purchase sent to GA servers. This process can ensure that revenue metrics reflect the actual spending in your game.

⚠️
Some configuration is needed before receipt validation will be active.
Read information about validation and requirements for different platforms here.

Receipt validation in Unity is supported for the following stores.

  • App Store (iOS)
  • Google Play Store (Android)

Add a business event with validation. Examples for iOS / Android.

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 – Google Play 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

⚠️
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. iOS7+ only.

⚠️
The method NewBusinessEventIOSAutoFetchReceipt will ignore business events on devices below iOS7. Specify the receipt manually to support older iOS versions.

ℹ️
Read more information about the business event here.

How to get receipts when using 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:

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

Resource Events

Resources events are used to track your in-game economy. From setting up the event you will be able to see three types of events in the tool. Flow, the total balance from currency spent and rewarded. Sink is all currency spent on items, and lastly source, being all currency rewarded in the game.

To add a resource event call the following function:

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.

ℹ️
For more information on the resource event go here.

Progression

Progression Events

Progression events are used to measure player progression in the game. They follow a 3 tier hierarchy structure (world, level, and phase) to indicate a player’s path or place.

To add a progression event call the following function:

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:

ℹ️
For more information on the progression event go here.

Error

Error Events

Used to track custom error events in the game. You can group the events by severity level and attach a message.

To add a custom error event call the following function:

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

ℹ️
For more information on the error event go here.

Design

Design Events

Used to track any type of design event that you want to measure i.e. GUI elements or tutorial steps. Custom dimensions are not supported for design events.

To add a design event call the following function:

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.

ℹ️
For more information on the design event go here.

ADDITIONAL CALLS

Set Custom Dimension

Set Custom Dimension

Sets one of three custom dimensions. The value used must be defined in the Setup tab of Settings.

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

Custom Dimension 1:

Custom Dimension 2:

Custom Dimension 3:

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.

ℹ️
Read more about custom dimensions here.

Set Facebook ID

Set Facebook Id

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:

Field Type Required Description
facebookId string yes Facebook id of the player.

Set Gender

Set Gender

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:

Field Type Required Description
gender string yes Gender of the player.

Set Birth Year

Set Birth Year

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:

Field Type Required Description
birthYear int yes Birth year of the player.

EXTRAS

PlayMaker

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. At this stage you should have already gone through the regular setup of the SDK described in the Setup section of the Wiki, starting with the Download and installation page.

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

Session Handling

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:

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()

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()

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.