Unity

Amplitude Unity Plugin Installation & Quick Start

Newest Releases

A plugin to simplify the integration of Amplitude iOS and Android SDKs into your Unity project. Our SDK will work with Unity 2019.3.11 and above.

🚧

Unity SDK does not 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.

Installation

1. Unity Package Manager

  • Ensure git is installed. In Unity, click Window > Package Manager. Click the plus + sign and select Add package from Git URL. Type in the URL https://github.com/amplitude/unity-plugin.git?path=/Assets, and then press Add. Wait for the Unity editor to import the package from Git.

1a. (alternative, manual download) Add dependency

  • Download the latest amplitude-unity.unitypackage from GitHub releases.
  • Double click amplitude-unity.unitypackage to import the package into your Unity project.

2. [Android] Add obfuscation exception

Please make sure you have this line in your Proguard rules file - proguard.pro.

-keep class com.amplitude.unity.plugins.AmplitudePlugin { *; }

3. Carrier information (Optional)

Please refer to this.

4. [Android] Dependencies Management

Our 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. We only use OkHttp, the other dependencies you see are ones OkHttp depends on (e.g. okio, jetbrain).

If by any chance you have OkHttp included in your project, feel free to choose not to include OkHttp and its related dependencies by unchecking them.

5. [Android] What if you're also using unity-jar-resolver?

Some users use unity-jar-resolver themselves. When they force resolve dependencies, it will clean up Amplitude related jars. For this case, what you would need to do is to declare those dependencies in your *Dependencies.xml file.

Please add our native dependencies under androidPackage tag.

    <androidPackage spec="com.amplitude:android-sdk:2.25.2">
      <repositories>
        <repository>https://maven.google.com</repository>
      </repositories>
    </androidPackage>

    <androidPackage spec="com.squareup.okhttp3:okhttp:4.2.2">
      <repositories>
        <repository>https://maven.google.com</repository>
      </repositories>
    </androidPackage>

6. [Android] API Compatibility

Running on API 19, 20 (KitKat)

Amplitude SDK depends on the OkHttp library. Since OkHttp v3.13 requires minimum version to be Android 5.0, Android Lollipop (API 21). Read details here.

We do not restrict which OkHttp version to use. For API 19, 20 to work, downgrade the OkHttp version to be lower than 3.13.

Android Instructions

Change the version of OkHttp to be lower than 3.13.

Unity Instructions

Import the library by copying the .jar file, you can downgrade okhttp library by replacing it with a version lower than 3.13.
If you use google dependency resolver, update the dependency version for okhttp in *Dependency.xml file.

iOS Instructions

For iOS, if xcode does not allow you to use a simulator or device, it is because the Unity project must be configured 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.

Usage & Examples

Initialization

Initialization is necessary before any instrumentation is done. The API key for your Amplitude project is required.

Amplitude amplitude = Amplitude.getInstance();
amplitude.setServerUrl("https://api2.amplitude.com");
amplitude.logging = true;
amplitude.trackSessionEvents(true);
amplitude.init("YOUR_API_KEY");

Optionally, you may send a string instanceName to getInstance(). This string is associated with all the settings of one Amplitude object.

Amplitude amplitude1 = Amplitude.getInstance("client_1");
Amplitude amplitude2 = Amplitude.getInstance("client_2");
//Settings changes in amplitude1 will not be reflected in amplitude2
Amplitude.getInstance("client_1") //this is the same reference as amplitude1

EU Data Residency

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 is set. The server zone config supports dynamic configuration as well.

For previous versions, you need to configure the serverURL property after initializing the client.

Warning: 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.

// For versions starting from 2.4.0
// No need to call setServerUrl for sending data to Amplitude's EU servers
amplitude.setServerZone(AmplitudeServerZone.EU);

// For earlier versions
amplitude.setServerUrl("https://api.eu.amplitude.com");

Sending Events

Basic Events

Events represent how users interact with your application. For example, “Button Clicked” may be an action you want to note.

amplitude.logEvent("Button Clicked");

When running this in Unity, please ensure that you have iOS or Android selected in the Build Settings under "Platform".

Events with Properties

Events can also contain properties. They provide context about the event taken. For example, “hover time” may be a relevant event property to “button click”.

Dictionary<string, object> eventProps = new Dictionary<string, object>();
eventProps.Add("Hover Time", 10);
amplitude.logEvent("Button Clicked", eventProps);

Set User Properties

🚧

Privacy and Tracking

Please be sure to not 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

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. The operations are declared via a provided Identify interface. Multiple operations can be chained together in a single Identify object. The Identify object is then passed to the Amplitude client to send to the server.

🚧

Identify Call

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.

Managing User Identity

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 operations (please check the Identify section) to Amplitude server to tie a user's events with specific user properties.

setUserProperty

setUserProperty sets the value of a user property. You can also chain together multiple identify calls.

amplitude.setUserProperty("saw_page_a", true);

setOnce

setOnce sets the value of a user property only once. Subsequent calls using setOnce will be ignored.

amplitude.setOnceUserProperty("page_views", 50);

add

add increments 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.

amplitude.addUserProperty("oranges", 5);
Dictionary<string, object> values = new Dictionary<string, object>();
values.Add("Key A", "Value A");
amplitude.addUserPropertyDict("user_facts", values);

Setting Multiple User Properties

logEvent() method allows you to 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 simply a wrapper around Identify.set.

Dictionary<string, object> values = new Dictionary<string, object>();
values.Add("user_time", 100.5);
values.Add("engagement", true);
amplitude.setUserProperties(values);

Arrays in User Properties

Arrays can be used as user properties. You can directly set arrays or use append (see section below this one) to generate an array.

int[] arr = new int[] { 1, 2, 4, 8 };
amplitude.setUserProperty("user_running_times", arr);

append

append 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 added. If the user property has an existing value and it is not a list, it will be converted into a list with the new value added.

amplitude.setUserProperty("stringArray", new string[]{"replace", "existing", "strings"});
amplitude.appendUserProperty("stringArray", new string[]{ "append", "more", "strings" });

Clearing User Properties

clearUserProperties method is for clearing all user properties at once. This will wipe all of the current user's user properties.

❗️

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.clearUserProperties();

unset

unset unsets and removes a user property.

amplitude.unsetUserProperty("property_name_to_unset");

Setting User Groups

📘

This feature is only available for Growth customers who have purchased the Accounts add-on.

Amplitude supports assigning users to groups and performing queries such as Count by Distinct on those groups. An example would be if you want to group your users based on what organization they are in by using an 'orgId'. You can designate Joe to be in 'orgId' '10' while Sue is in 'orgId' '15'. When performing a query in our Event Segmentation chart, you can then select "..performed by" 'orgId' to query the number of different organizations that have performed a specific event. As long as at least one member of that group has performed the specific event, that group will be included in the count.

When setting groups, you will need to define a groupType and groupName(s). In the above example, 'orgId' is the groupType and the values '10' and '15' are groupName(s). Another example of a groupType could be 'sport' with groupName(s) like 'tennis' and 'baseball'. You can use setGroup(groupType, groupName) to designate which groups a user belongs to. Note: This will also set the 'groupType:groupName' as a user property. This will overwrite any existing groupName value set for that user's groupType, as well as the corresponding user property value. groupType is a string and groupName can be either a string or an array of strings to indicate a user being in multiple groups (for example, if Joe is in 'orgId' '10' and '16', then the groupName would be '[10, 16]'). Here is what your code might look like:

Amplitude.getInstance().setGroup("orgId", "15");
Amplitude.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 does not persist on the user unless you explicitly set it with setGroup:

JSONObjecteventProperties=newJSONObject().put("key", "value");
JSONObjectgroups=newJSONObject().put("orgId", 10);

Amplitude.getInstance().logEvent("initialize_game", eventProperties, groups);

Track Revenue

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

NameTypeDescriptionDefault
productId (optional)stringAn identifier for the product. We recommend something like the Google Play Store product ID.null
quantity (required)integerThe quantity of products purchased. Note: revenue = quantity * price1
price (required)doubleThe price of the products purchased, and this can be negative. Note: revenue = quantity * pricenull
revenueType (optional)stringThe type of revenue (e.g. tax, refund, income).null
eventProperties (optional)objectAn object of event properties to include in the revenue event.null

📘

Price can be negative, which may be useful for tracking revenue lost (such as refunds or costs)

Revenue Verification

Note that since Unity supports both Android and iOS store, consult the proper documentation for revenue verification. Take a look at the Android and iOS/tvOS/macOS documentation, as well as special instructions for the store (Android AIDL/Google Play Billing, Amazon Store, or iOS App Store).

amplitude.logRevenue(0.03);
amplitude.logRevenue("sku", 1, 1.99);
amplitude.logRevenue("sku", 1, 1.99, "cmVjZWlwdA==", null);
Dictionary<string, object> revenueProperties = new Dictionary<string, object>()
{
  {"car", "blue"},
  {"price", 12.99}
};
if (Application.platform == RuntimePlatform.IPhonePlayer) {
  amplitude.logRevenue("sku", 1, 1.99, "cmVjZWlwdA==", null, "purchase", revenueProperties);
} else if (Application.platform == RuntimePlatform.Android) {
  amplitude.logRevenue("sku", 1, 1.99, "receipt", "receiptSignature", "purchase", revenueProperties);
}

🚧

Amplitude currently does not support currency conversion. All revenue data should be normalized to a currency of choice before being sent to Amplitude.

User Sessions

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 will have the same session_id. Sessions are handled automatically so you do not have to manually call an API like startSession() or endSession().

You can adjust the time window for which sessions are extended.

client.setMinTimeBetweenSessionsMillis(10000); //10 seconds

By default, '[Amplitude] Start Session' and '[Amplitude] End Session' events are not 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. Internally (in Amplitude dashboards), 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().

Dictionary<string, object> eventProps = new Dictionary<string, object>();
bool outOfSession = true;
client.logEvent("event out of session", eventProps, outOfSession);

Advertising ID & Location Tracking (GPS)

Advertiser ID (also referred to as IDFA) is a unique identifier provided by the iOS and Google Play stores. As it is unique to every person and not just their devices, it is useful for mobile attribution. Mobile attribution is the attribution of an installation of a mobile app to its original source (e.g. ad campaign, app store search). Mobile apps need permission to ask for IDFA, and apps targeted to children cannot track at all. Consider IDFV, device id, or an email login system as alternatives when IDFA is not available.

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.

❗️

Unity for iOS

Please see the Unity iOS IDFA and GPS setup guide to handle privacy restrictions and permissions.

Setting Custom User ID

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 can also add the User ID as an argument to the init call.

Amplitude.Instance.init("API_KEY", "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.

Advanced Topics

COPPA Control

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.

client.enableCoppaControl();

Opt Out of Tracking

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.

client.setOptOut(true); //No events will be tracked for this user

Dynamic Configuration

Unity SDK allows users to configure their apps to use dynamic configuration. This feature will find the best server url automatically based on app users' geo location.

  • If you have your own proxy server and use setServerUrl API, please leave this OFF.
  • If you have users in China Mainland, we suggest you turn this on.
  • By default, this feature is OFF. So you need to explicitly set it to ON to use it.
  • By default, this feature returns server url for Amplitude's US servers, if you need to send data to Amplitude's EU servers, please use setServerZone to set it to EU zone.
amplitude.setUseDynamicConfig(true);

Need Help?

If you have any problems or issues over our SDK, feel free to create a github issue or submit a request on Amplitude Help.


Did this page help you?