The Amplitude Unity plugin simplifies the integration of the Amplitude iOS and Android SDKs into your Unity project. The variables and values in red are what you will need to replace with your own. This repository contains a sample project with the Unity plugin integrated. You can open the project and replace the API Key in AmplitudeDemo.cs with your key to see how the integration works.
For iOS and Android specific documentation, see the iOS and Android SDK installation articles. The source code for Amplitude's Unity plugin can be found on GitHub here. For best practices on instrumenting Amplitude, see our Getting Started Guide for developers and sign up for one of our instrumentation training seminars here. Also, for more developer specific content, please feel free to check out our Developer Centre here.
Click here to view the Unity Plugin Changelog.
Table of Contents
- Installation
- Tracking Events
- Tracking Sessions
- Setting Custom User IDs
- Setting Event Properties
- Setting User Properties
- Tracking Revenue
- Opting User Out of Logging
- Advanced
Installation
1. Create an Amplitude account. If you have not already, go to https://amplitude.com and register for an account. Then, create an organization and a project. You will immediately receive an API Key for the project you have just created.
2. Download the code. Download the plugin package here.
3. Initialize the plugin with your API Key. In the Awake method in your main script, initialize and enable the Amplitude plugin:
void Awake () { Amplitude amplitude = Amplitude.Instance; amplitude.logging = true; amplitude.init("API_KEY"); }
Replace API_KEY
with the API Key given to you. You can find your project's API Key in your project's Settings page.
4. Start tracking events. Data is sent to Amplitude via events. As a result, you will have to explicitly log events in order to see any data in your project. To track an event anywhere in the app, call:
Amplitude.Instance.logEvent("EVENT_TYPE");
where EVENT_TYPE
is the name you are giving to the event you want to track.
5. Build your Unity project to an iOS or Android app. The Unity plugin is only a wrapper around Amplitude's native iOS and Android SDKs, so you will need to build to an iOS or Android app and run it in a simulator or on a test device to trigger the native SDKs to log events.
6. Event uploads. Events are saved locally by our native SDKs. Uploads are batched to occur every 30 events and every 30 seconds. After calling logEvent()
in your app, you will immediately see data appear in Amplitude.
Note: If you are building your Unity project as an iOS app, Amplitude's iOS SDK requires the SQLite library, which is included in iOS but may require an additional build flag to enable. In Xcode, add the flag -lsqlite3.0
under Linking
-> Other Linker Flags
in your project's Build Settings
and your Target's Build Settings
.
Tracking Events
It is important to consider what types of events you care about as a developer. You should aim to track between 20 and 200 types of events on your site. Common event types are actions the user initiates (such as pressing a button) and events you want the user to complete (such as filling out a form, completing a level, or making a payment).
Here are some resources to help you with your taxonomy or instrumentation planning:
Having a large number of distinct event types, event properties, and user properties can make data exploration and visualization very confusing. By default, we only show the first:
- 2000 distinct event types
- 2000 distinct event properties
- 1000 distinct user properties
Anything past the above thresholds will not be visualized. Note: The raw data is not impacted by this in any way, meaning that you will still see the values in the raw data but they will not be visualized in the platform. A single call to logEvent
should not have more than 1000 event properties. Likewise, a single call to setUserProperties
should not have more than 1000 user properties. If the 1000 property limit is exceeded then the properties will be dropped and a warning will be printed in the console. We have put in very conservative estimates for the event type and property caps that we do not expect to be exceeded in any practical use case. If you feel that your use case will go above those limits, please reach out to us here.
To track an event anywhere in the app, call:
Amplitude.Instance.logEvent("EVENT_TYPE");
where EVENT_TYPE
is the name you are giving to the event you want to track.
Tracking Sessions
A session is a period of time that a user has the app in the foreground. Events that are logged within the same session will have the same session_id
. Sessions are handled automatically so you do not have to manually call startSession()
or endSession()
.
By default, '[Amplitude] Start Session' and '[Amplitude] End Session' events are no longer sent. Even though these events are not sent, sessions are still tracked by using session_id
. To re-enable those session events, add this line before initializing the SDK:
Amplitude amplitude = Amplitude.Instance; amplitude.trackSessionEvents(true); amplitude.init("API_KEY");
You can also log events as out-of-session. Out-of-session events have a session_id
of -1
and are not considered part of the current session, meaning they do not extend the current session. This might be useful if you are logging events triggered by push notifications, for example. You can log events as out-of-session by setting the input parameter outOfSession
to true
when calling logEvent()
:
Amplitude.Instance.logEvent("EVENT_TYPE", null, true);
Getting the Session ID
You can use the helper method getSessionId
to get the value of the current Session ID:
long sessionId = Amplitude.Instance.getSessionId();
Setting Custom User IDs
If your app has its own login system that you want to track users with, you can call setUserId()
at any time:
Amplitude.Instance.setUserId("USER_ID");
You should not assign users a User ID that could change as each unique User ID is interpreted as a unique user in Amplitude. Please see our article on how we identify and count unique users for further information. A user's data will be merged on the backend so any events up to that point on the same device will be tracked under the same user. You can also add a User ID as an argument to the init()
call:
Amplitude.Instance.init("API_KEY", "USER_ID");
Setting Event Properties
You can send event property attributes to any event by passing a JSONObject as the second argument to logEvent()
:
Dictionary<string, object> demoOptions = new Dictionary<string, object>() { {"Bucket" , "A" }, {"Credits" , 9001} }; Amplitude.Instance.logEvent("Sent Message", demoOptions);
Setting User Properties
IMPORTANT NOTE: Please be sure to not track any user data that may be against your privacy terms. If you need any assistance with privacy concerns, please reach out to our Platform team here.
The Amplitude Unity Plugin supports the operations set
, setOnce
, unset
, and add
on individual user properties. Each operation is performed on a single user property and updates its value accordingly. The method names follow the format of operationUserProperty
. For example, to use the set
operation you would call setUserProperty
. The provided method signatures will tell you what value types are allowed for each operation.
set
: This sets the value of a user property.Amplitude.Instance.setUserProperty("gender", "female"); // string value Amplitude.Instance.setUserProperty("age", 20); // int value Amplitude.Instance.setUserProperty("some float values", new float[]{20f, 15.3f, 4.8f}); // float array
setOnce
: This sets the value of a user property only once. SubsequentsetOnce
operations on that user property will be ignored. In the following example, 'sign_up_date' will be set once to '2015-08-24', and the followingsetOnce
to '2015-09-14' will be ignored.Amplitude.Instance.setOnceUserProperty("sign_up_date", "08/24/2015"); Amplitude.Instance.setOnceUserProperty("sign_up_date", "09/14/2015");
unset
: This will unset and remove a user property.Amplitude.Instance.unsetUserProperty("sign_up_date"); Amplitude.Instance.unsetUserProperty("age");
add
: This will increment a user property by some numerical value. If the user property does not have a value set yet, it will be initialized to 0 before being incremented. Note: String values are allowed as they will be converted to their numerical equivalent. Dictionary values are also allowed as they will be flattened during processing.Amplitude.Instance.addUserProperty("karma", 1.5); Amplitude.Instance.addUserProperty("friends", 1);
append
: This will append a value or values to a user property array. If the user property does not have a value set yet, it will be initialized to an empty list before the new values are appended. If the user property has an existing value and it is not on a list, it will be converted into a list with the new value appended.Amplitude.Instance.appendUserProperty("ab-tests", "new_user_tests"); Amplitude.Instance.appendUserProperty("some_list", new int[]{1, 2, 3, 4});
Arrays in User Properties
The Unity Plugin supports arrays in user properties. Any of the user property operations above (with the exception of add
) can accept an arrays and lists. You can directly set
arrays or use append
to generate an array. Here is an example:
List<double> list = new List<double>(); list.add(2.5); list.add(6.8); Amplitude.Instance.appendUserProperty("my_list", list);
Setting Multiple User Properties
You may use setUserProperties
shorthand to set multiple user properties at once. This method is simply a wrapper around Identify.set
and identify
. Here is an example:
Dictionary<string, object> userProperties = new Dictionary<string, object>() { {"float_gprop", 1.0} }; Amplitude.Instance.setUserProperties(userProperties);
Clearing User Properties
You may use clearUserProperties
to clear all user properties at once. This will wipe all of the current user's user properties. Note: The result is irreversible! Amplitude will not be able to sync the user's user property values before the wipe to any future events that the user triggers as they will have been reset.
Amplitude.Instance.clearUserProperties();
Default Amplitude Properties Tracking
By default, the Unity Plugin is automatically tracking the location and Carrier properties, however, you can customize these options. To use, pass a Dictionary mapping the respective disable option string to true
. Example:
Dictionary<string, bool> trackingOptions = new Dictionary<string, bool>();
trackingOptions.Add("disableCity", true);
trackingOptions.Add("disableIPAddress", true);
trackingOptions.Add("disableIDFV", true);
trackingOptions.Add("disableIDFA", true);
trackingOptions.Add("disableCountry", true);
trackingOptions.Add("disableCarrier", true);
trackingOptions.Add("disableADID", true);
Amplitude.Instance.setTrackingOptions(trackingOptions);
Tracking Revenue
To track revenue from a user, call logRevenue() each time a user generates revenue. Here is an example:
Amplitude.Instance.logRevenue("com.company.productid", 1, 3.99);
logRevenue()
takes a string to identify the product (for example, the Product ID from the Google Play Store), an int with the quantity of product purchased, and a double with the dollar amount of the sale. This allows us to automatically display data relevant to revenue in the platform in places like the Revenue Analysis and Revenue LTV charts. Calling logRevenueV2
will generate up to 2 different event types in the platform:
- '[Amplitude] Revenue': This event is logged for all revenue events, regardless of whether or not verification is turned on.
- '[Amplitude] Revenue (Verified/Unverified)': These revenue events will contain the actual '$revenue' property.
You cannot change the default names given to these client-side revenue events in the raw data but you do have the option to modify the display name. To learn more about tracking revenue, see our documentation here.
Revenue Verification
The logRevenue
method also supports revenue validation. See the iOS and Android specific installation documentation, as well as Unity documentation for more details. Here is a simple example:
if (Application.platform == RuntimePlatform.IPhonePlayer) {
Amplitude.Instance.logRevenue("sku", 1, 1.99, "cmVjZWlwdA==", null);
} else if (Application.platform == RuntimePlatform.Android) {
Amplitude.Instance.logRevenue("sku", 1, 1.99, "receipt", "receiptSignature");
}
The logRevenue method also allows for tracking 'revenueType' and event properties on the revenue event. Here is an example:
Dictionary<string, object> eventProperties = new Dictionary<string, object>() {
{"Bucket" , "A" },
{"color" , "blue"}
};
if (Application.platform == RuntimePlatform.IPhonePlayer) {
Amplitude.Instance.logRevenue("sku", 1, 1.99, "cmVjZWlwdA==", null, "purchase", eventProperties);
} else if (Application.platform == RuntimePlatform.Android) {
Amplitude.Instance.logRevenue("sku", 1, 1.99, "receipt", "receiptSignature", "purchase", eventProperties);
}
Opting User Out of Logging
To stop all event and session logging for a user, call setOptOut
:
Amplitude.Instance.setOptOut(true);
Logging can be restarted by calling setOptOut
again and have it set to false
. No events will be logged during the period this is enabled.
Advanced
Setting Date Values
Amplitude compares dates as strings, so it is recommended to use the ISO 8601 format (YYYY-MM-DDTHH:mm:ss), which will allow you to perform date comparisons in the platform (e.g. '2016-01-31' > '2016-01-01'). This will also work for datetime values (e.g. '2017-08-07T10:09:08' > '2017-08-07T01:07:00').
Improved Android Dependencies
Android dependencies are now separated instead of merging 3rd party libraries with the Amplitude ones. This gives customers the freedom to chose which libraries they want use in order to avoid conflicts with their other dependencies.
Running on API 19, 20 (KitKat)
Amplitude SDK depends on okhttp library, since okhttp v3.13, they require android 5.0, Android Lollipop (API 21). Read details
We do not restrict which okhttp version to use, you can downgrade the okttp version to be lower than 3.13 to make it work for API 19, 20.
How to downgrade?
If you import library by copying the jar file, you can downgrade okhttp library by replacing it with a version < 3.13. If you use google dependency resolver, update the dependency version for okhttp in *Dependency.xml file.