The Amplitude Analytics Unity SDK is a plugin to simplify the integration of Amplitude iOS and Android SDKs into your Unity project. This SDK works with Unity 2019.3.11 and higher.
Unity SDK doesn't support pure desktop or Editor
Remember to test your apps using the Build Settings
for either Android or iOS, which links to their respective devices or emulators.
The Amplitude Analytics Unity SDK supports different methods of installation, depending on the platform.
Window > Package Manager
.Add package from Git URL
.https://github.com/amplitude/unity-plugin.git?path=/Assets
, and then click Add.amplitude-unity.unitypackage
from GitHub releases.amplitude-unity.unitypackage
to import the package into your Unity project.Add this line in your ProGuard rules file - proguard.pro
.
1-keep class com.amplitude.unity.plugins.AmplitudePlugin { *; }
Amplitude's com.amplitude.android-sdk
is a transitive library, it doesn't include any other dependencies by itself. Other dependencies for com.amplitude.android-sdk
are placed into Assets/Plugins/Android
. Amplitude uses OkHTTP, and the other dependencies you see are ones OkHTTP depends on (for example, Okio or Jetbrains).
If you use OkHTTP in your project, you can choose not to include OkHTTP and its related dependencies by unchecking them.
Some users use unity-jar-resolver
themselves. When they force resolve dependencies, it cleans up Amplitude-related jars. In this case, declare those dependencies in your *Dependencies.xml
file.
Add Amplitude's native dependencies under androidPackage
tag.
1<androidPackage spec="com.amplitude:android-sdk:2.+"> 2 <repositories> 3 <repository>https://maven.google.com</repository> 4 </repositories> 5</androidPackage> 6 7<androidPackage spec="com.squareup.okhttp3:okhttp:4.2.2"> 8 <repositories> 9 <repository>https://maven.google.com</repository>10 </repositories>11</androidPackage>
The Amplitude Analytics Unity SDK depends on the OkHTTP library. OkHTTP v3.13 requires the minimum version to be Android 5.0, Android Lollipop (API 21). Read details here.
Amplitude doesn't restrict which OkHTTP version to use. For API 19, 20 (Android KitKat) to work, downgrade the OkHTTP version to be lower than 3.13.
*Dependency.xml
file.If Xcode doesn't let you use a simulator or device, it's because you must configure the Unity project to use either the Device SDK (real life devices) or the Simulator SDK (emulator).
To change the settings for the build, select Unity > Edit > Project Settings... > Player > iOS Tab
, open the dropdown menu Other Settings, scroll to Configuration, and select either value needed for the Target SDK field.
Initialization is necessary you can do instrumentation. The API key for your Amplitude project is required.
1Amplitude amplitude = Amplitude.getInstance();2amplitude.setServerUrl("https://api2.amplitude.com");3amplitude.logging = true;4amplitude.trackSessionEvents(true);5amplitude.init(AMPLITUDE_API_KEY);
Optionally, you may send a string instanceName
to getInstance()
. This string is associated with all the settings of one Amplitude
object.
1Amplitude amplitude1 = Amplitude.getInstance("client_1");2Amplitude amplitude2 = Amplitude.getInstance("client_2");3//Settings changes in amplitude1 will not be reflected in amplitude24Amplitude.getInstance("client_1") //this is the same reference as amplitude1
Amplitude Unity SDK runs on the top of the Amplitude Android Maintenance SDK, and Amplitude iOS Maintenance SDK. The following are the C# settable config options.
For other default configurations:
Name | Description | Default Value |
---|---|---|
enableCoppaControl() |
Enable COPPA (Children's Online Privacy Protection Act) restrictions on IDFA, IDFV, city, IP address and location tracking. | Coppa control is disabled by default. |
disableCoppaControl() |
Disable COPPA (Children's Online Privacy Protection Act) restrictions on IDFA, IDFV, city, IP address and location tracking. | Coppa control is disabled by default. |
setTrackingOptions() |
IDictionary<string, bool> . By default the SDK will track several user properties such as carrier, city, country, ip_address, language, platform, etc. |
All tracking options enabled. |
setMinTimeBetweenSessionsMillis() |
long . The amount of time for session timeout if disable foreground tracking. For example, Amplitude.getInstance().setMinTimeBetweenSessionsMillis(100000) . The input parameter is in milliseconds. |
5 minutes |
setEventUploadPeriodSeconds() |
int . Events wait in the buffer and are sent in a batch. The buffer is flushed every eventUploadPeriodSeconds or reach 30 events threshold. For example, Amplitude.getInstance().setEventUploadPeriodSeconds(50) . The input parameter is in seconds. |
30 seconds |
setServerZone() |
AmplitudeServerZone . The server zone of the projects. Supports EU and US. For EU data residency, change to EU. For example, Amplitude.getInstance().setServerZone(AmplitudeServerZone.US) . |
AmplitudeServerZone.US |
setServerUrl() |
string . The API endpoint URL that events are sent to. Automatically selected by ServerZone . For example, Amplitude.getInstance().setServerUrl(https://www.your-server-url.com) . |
https://api2.amplitude.com/ |
setUseDynamicConfig() |
bool . Find the best server url automatically based on users' geo location. For example, Amplitude.getInstance().setUseDynamicConfig(true) . |
false |
setOffline() |
bool . Weather the SDK will upload events to Amplitude servers. However, the SDK will always log events. For example, Amplitude.getInstance().setOffline(true) . |
false |
useAdvertisingIdForDeviceId() |
bool . Whether to use advertising id as device id. Check here for the required module and permission. For example, Amplitude.getInstance().useAdvertisingIdForDeviceId(true) . |
The deviceId will be UUID+"R" by default. |
useAppSetIdForDeviceId() |
bool . Only for Android. Whether use appset id as a deviceId. Check here for the required module and permission. For example, Amplitude.getInstance().useAppSetIdForDeviceId(true) . |
The deviceId will be UUID+"R" by default. |
To support high-performance environments, the SDK sends events in batches. Every event logged by the logEvent
method is queued in memory. Events are flushed in batches in background. You can customize batch behavior with setEventUploadPeriodSeconds
. By default, the serverUrl will be https://api2.amplitude.com/
. This SDK doesn't support batch mode, the batch API endpoint.
1// Events queue will flush every certain seconds based on setting2// Default value is 30 seconds3amplitude.setEventUploadPeriodSeconds(50);
Starting from version 2.4.0, you can configure the server zone after initializing the client for sending data to Amplitude's EU servers. SDK will switch and send data based on the server zone if it's set.
The server zone configuration supports dynamic configuration as well.
For earlier versions, you need to configure the serverURL
property after initializing the client.
For EU data residency, project need to be set up inside Amplitude EU and SDK initialized with API key from Amplitude EU first. This method won't work without proper set up first.
1// For versions starting from 2.4.02// No need to call setServerUrl for sending data to Amplitude's EU servers3amplitude.setServerZone(AmplitudeServerZone.EU);4 5// For earlier versions6amplitude.setServerUrl("https://api.eu.amplitude.com");
Events represent how users interact with your application. For example, "Button Clicked" may be an action you want to note.
1amplitude.logEvent("Button Clicked");
When running this in Unity, make sure that you have iOS or Android selected in the Build Settings under "Platform".
Events can also contain properties. They give context about the event taken. For example, "hover time" may be a relevant event property to "button click".
1Dictionary<string, object> eventProps = new Dictionary<string, object>();2eventProps.Add("Hover Time", 10);3amplitude.logEvent("Button Clicked", eventProps);
Don't track any user data that may be against your privacy terms. If you need any assistance with privacy concerns, then please reach out to our Platform team.
Identify is for setting the user properties of a particular user without sending any event. The Unity SDK supports the operations setUserProperty
, setOnce
, add
, and append
on individual user properties.
Declare the operations with a provided Identify interface. Chain together multiple operations in a single Identify object. The Identify object is then passed to the Amplitude client to send to the server.
If the Identify call is sent after the event, the results of operations will be visible immediately in the dashboard user's profile area, but it will not appear in chart result until another event is sent after the Identify call. So the identify call only affects events going forward. More details here.
You can handle the identity of a user using the identify methods. Proper use of these methods can connect events to the correct user as they move across devices, browsers, and other platforms.
Send an identify call containing those user property operation to Amplitude to tie a user's events with specific user properties.
setUserProperty
sets the value of a user property. You can also chain together multiple identify calls.
1amplitude.setUserProperty("saw_page_a", true);
setOnce
sets the value of a user property only once. Subsequent calls using setOnce
will be ignored.
1amplitude.setOnceUserProperty("page_views", 50);
add
increments a user property by some numerical value. If the user property doesn't have a value set yet, it's initialized to 0.
1amplitude.addUserProperty("oranges", 5);2Dictionary<string, object> values = new Dictionary<string, object>();3values.Add("Key A", "Value A");4amplitude.addUserPropertyDict("user_facts", values);
logEvent()
method lets you set the user properties along with event logging. You can use setUserProperties
as a shorthand to set multiple user properties at once. This method is a wrapper around Identify.set
.
1Dictionary<string, object> values = new Dictionary<string, object>();2values.Add("user_time", 100.5);3values.Add("engagement", true);4amplitude.setUserProperties(values);
Arrays can be used as user properties. You can directly set arrays or use append
to generate an array.
1int[] arr = new int[] { 1, 2, 4, 8 };2amplitude.setUserProperty("user_running_times", arr);
append
appends a value or values to a user property array. If the user property doesn't have a value set yet, it's initialized to an empty list before the new values are added.
If the user property has an existing value and it's not a list, it will be converted into a list with the new value added.
1amplitude.setUserProperty("stringArray", new string[]{"replace", "existing", "strings"});2amplitude.appendUserProperty("stringArray", new string[]{ "append", "more", "strings" });
clearUserProperties
method is for clearing all user properties at one time.
Amplitude doesn't sync the user's user property values before the wipe to any future events that the user triggers as they will have been reset.
1amplitude.clearUserProperties();
unset
unsets and removes a user property.
1amplitude.unsetUserProperty("property_name_to_unset");
Amplitude supports assigning users to groups and performing queries, such as Count by Distinct, on those groups. If at least one member of the group has performed the specific event, then the count includes the group.
For example, you want to group your users based on what organization they're in by using an 'orgId'. Joe is in 'orgId' '10', and Sue is in 'orgId' '15'. Sue and Joe both perform a certain event. You can query their organizations in the Event Segmentation Chart.
When setting groups, define a groupType
and groupName
. In the previous example, 'orgId' is the groupType
and '10' and '15' are the values for groupName
. Another example of a groupType
could be 'sport' with groupName
values like 'tennis' and 'baseball'.
Setting a group also sets the groupType:groupName
as a user property, and overwrites any existing groupName
value set for that user's groupType
, and the corresponding user property value. groupType
is a string, and groupName
can be either a string or an array of strings to indicate that a user is in multiple groups.
This example shows a groupType "orgID" with a groupName of "15". The second line shows a groupType "sport" with "tennis" and "soccer" as groupNames.
1Amplitude.getInstance().setGroup("orgId", "15");2Amplitude.getInstance().setGroup("sport", new JSONArray().put("tennis").put("soccer")); // list values
You can also use logEventWithGroups
to set event-level groups, meaning the group designation only applies for the specific event being logged and doesn't persist on the user unless you explicitly set it with setGroup
:
1JSONObjecteventProperties=newJSONObject().put("key", "value");2JSONObjectgroups=newJSONObject().put("orgId", 10);3 4Amplitude.getInstance().logEvent("initialize_game", eventProperties, groups);
Amplitude can track revenue generated by a user. Revenue is tracked through distinct revenue objects, which have special fields that are used in Amplitude's Event Segmentation and Revenue LTV charts. This allows Amplitude to automatically display data relevant to revenue in the platform. Revenue objects support the following special properties, as well as user-defined properties through the eventProperties
field.
Calling logRevenue
generates up to 2 different event types in the platform:
You can't 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 the documentation here.
Name | Description |
---|---|
productId |
Optional. String. An identifier for the product. Amplitude recommends something like the "Google Play Store product ID". Defaults to null . |
quantity |
Required. Integer. The quantity of products purchased. Note: revenue = quantity * price. Defaults to 1. |
price |
Required. Double. The price of the products purchased, and this can be negative. Note: revenue = quantity * price. Defaults to null . |
revenueType |
Optional, but required for revenue verification. String. The type of revenue (for example, tax, refund, income). Defaults to null . |
eventProperties |
Optional. Object. An object of event properties to include in the revenue event. Defaults to null . |
Price can be negative, which may be useful for tracking revenue lost (such as refunds or costs)
Because Unity supports both Android and iOS store, consult the proper documentation for revenue verification.
See the Android and iOS/tvOS/macOS documentation, and special instructions for the store (Android AIDL/Google Play Billing, Amazon Store, or iOS App Store).
1amplitude.logRevenue(0.03); 2amplitude.logRevenue("sku", 1, 1.99); 3amplitude.logRevenue("sku", 1, 1.99, "cmVjZWlwdA==", null); 4Dictionary<string, object> revenueProperties = new Dictionary<string, object>() 5{ 6 {"car", "blue"}, 7 {"price", 12.99} 8}; 9if (Application.platform == RuntimePlatform.IPhonePlayer) {10 amplitude.logRevenue("sku", 1, 1.99, "cmVjZWlwdA==", null, "purchase", revenueProperties);11} else if (Application.platform == RuntimePlatform.Android) {12 amplitude.logRevenue("sku", 1, 1.99, "receipt", "receiptSignature", "purchase", revenueProperties);13}
Amplitude doesn't support currency conversion. All revenue data should be normalized to your currency of choice before being sent.
A session on Android is a period of time that a user has the app in the foreground.
Amplitude groups events together by session. Events that are logged within the same session have the same session_id
. Sessions are handled automatically so you don't have to manually call an API like startSession()
or endSession()
.
You can adjust the time window for which sessions are extended.
1client.setMinTimeBetweenSessionsMillis(10000); //10 seconds
By default, '[Amplitude] Start Session' and '[Amplitude] End Session' events aren't sent. Even though these events aren't sent, sessions are still tracked by using session_id
.
To re-enable those session events, add this line before initializing the SDK.
1Amplitude amplitude = Amplitude.Instance;2amplitude.trackSessionEvents(true);3amplitude.init(AMPLITUDE_API_KEY);
You can also log events as out-of-session. Internally (in Amplitude dashboards), out-of-session events have a session_id
of -1
and aren't considered part of the current session, meaning they don't 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()
.
1Dictionary<string, object> eventProps = new Dictionary<string, object>();2bool outOfSession = true;3client.logEvent("event out of session", eventProps, outOfSession);
Advertiser ID (also referred to as IDFA) is a unique identifier provided by the iOS and Google Play stores. Because it's unique to every person and not just their devices, IDFA is useful for mobile attribution. Mobile attribution is the attribution of an installation of a mobile app to its original source (for example, ad campaign, app store search).
Mobile apps need permission to ask for IDFA, and apps targeted to children can't track at all. Consider IDFV, device id, or an email login system as alternatives when IDFA isn't available.
See setup instructions in Unity iOS IDFA and GPS Setup.
See setup instructions in the Android SDK.
For location tracking, Amplitude converts the IP of a user event into a location (GeoIP lookup) by default. This information may be overridden by an app's own tracking solution or user data.
Amplitude can access the Android location service (if possible) to add the specific coordinates (longitude and latitude) where an event is logged.
If your app has its login system that you want to track users with, you can call setUserId
at any time.
1Amplitude.Instance.setUserId("USER_ID");
You can also add the User ID as an argument to the init call.
1Amplitude.Instance.init(AMPLITUDE_API_KEY, "USER_ID");
Don't assign users a User ID that could change as each unique User ID is interpreted as a unique user in Amplitude.
See Track unique users in Amplitude for more information.
COPPA (Children's Online Privacy Protection Act) restrictions on IDFA, IDFV, city, IP address and location tracking can be enabled or disabled all at once.
Remember that apps asking for information from children under 13 years of age must comply with COPPA.
1client.enableCoppaControl();
Users may wish to opt out of tracking entirely, which means no events and no records of their browsing history. This API provides a way to fulfill certain users' requests for privacy.
1client.setOptOut(true); //No events will be tracked for this user
Unity SDK allows users to configure their apps to use dynamic configuration. This feature finds the best Amplitude server URL automatically based the user's location.
setServerUrl
API, don't use dynamic configuration.setServerZone
to set it to EU zone.1amplitude.setUseDynamicConfig(true);
This section walks through the process to give Unity SDK users access to IDFA (advertiser ID) and GPS coordinate data in their logged events.
If an app is subject to COPPA because it's aimed toward children, the app can't contain any IDFA or GPS tracking code. This is why the IDFA and GPS code requires additional setup.
First, take the two files unity-plugin/IdfaIOS/CustomIdfa.m
and unity-plugin/IdfaIOS/CustomGPS.m
and place them into Assets/Scripts
.
You may place the file wherever, but check all the #import
statements lead to correct paths.
In the imports section (the top) of your .cs
game script, add this import:
1#if (UNITY_IPHONE || UNITY_TVOS)2using System.Runtime.InteropServices;3#endif
Inside the game class, add the following code inside your MonoBehavior class, or any other class.
1public class AmplitudeDemo : MonoBehavior {2 3#if (UNITY_IPHONE || UNITY_TVOS)4 [DllImport ("__Internal")]5 private static extern void setIdfaBlock(string instanceName);6 [DllImport ("__Internal")]7 private static extern void setLocationInfoBlock(string instanceName);8#endif
Finally, in your game code, probably in void Start()
, call these functions. YOUR_INSTANCE_NAME
is a string associated with this particular instance of Amplitude. YOUR_INSTANCE_NAME
may also be null or an empty string.
1Amplitude amplitude = Amplitude.getInstance(YOUR_INSTANCE_NAME);2amplitude.init(AMPLITUDE_API_KEY);3 4#if (UNITY_IPHONE || UNITY_TVOS)5 setLocationInfoBlock(YOUR_INSTANCE_NAME);6 setIdfaBlock(YOUR_INSTANCE_NAME);7#endif
These functions prompt the iOS user to accept or reject permissions for GPS location tracking, as well as IDFA tracking.
Your Unity app needs two special configurations.
For location, navigate to Unity > Edit > Project Settings...
. The menu in the first image below will pop up. Select Player
, then click the iOS
tab. Click Other Settings
, and scroll until the field Location Usage Description
. Type a sentence that prompts the user for GPS tracking permissions into the text box.
IDFA tracking permissions can generally only be tested reliably on real life phones.
For IDFA, the file Info.plist
has to be edited according to Apple's specifications. This can be done with a Unity script with guidance from this Unity post.
Also, when the app is compiled into iOS and launches into Xcode, find the top-level file Info.plist
. Click the plus symbol next to any key value pair. Use the Xcode editor to find the key Privacy - Tracking Usage Description
, make sure the Type is String, and type a prompt to ask for tracking permission in the Value field.
Thanks for your feedback!
July 23rd, 2024
Need help? Contact Support
Visit Amplitude.com
Have a look at the Amplitude Blog
Learn more at Amplitude Academy
© 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.