Unity SDK integration for developers


Current Unity SDK Version: v4.20.3
Based on AppsFlyer Android SDK v4.10.2 and AppsFlyer iOS SDK v4.10.4

1. Overview

AppsFlyer’s Unity SDK provides mobile app installation and event recording functionality for Android and iOS Unity projects. You can record installs, updates, and sessions and also record post-installs events (including in-app purchases, game levels, etc.) to evaluate ROI and user engagement levels.

Mobile apps, that are developed on the Unity platform, can integrate AppsFlyer's SDK once and attribution installs for both Android and iOS generated apps. The following guide details how to integrate AppsFlyer's SDK into your Unity code for your iOS and Android apps.


AppsFlyer supports integration with Unity version 5 and above


Google Play Install Referrer API is supported starting from Unity Plugin v 4.16.0. If you want to use the new Referrer API, update the plugin to version 4.16.0 or above.


  • Chapters 2 and 3 are MANDATORY to implement BASIC SDK integration, i.e. install attribution only
  • Recording in-app events chapter is HIGHLY RECOMMENDED to implement
  • The rest of the described features are OPTIONAL to implement, although some of them may be necessary for you, depending on your app's business logic. For example, recording revenue or getting the conversion data on first launch may be vital for your app's flow

2. Quick start

2.1 Downloading AppsFlyer's Unity plugin

You can find the plugin on Github here: https://github.com/AppsFlyerSDK/Unity

Set out below are the integration instructions for using AppsFlyer’s Unity Plugin.

2.2 installing the plugin

Set out below are the installation instructions for the AppsFlyer's plugin:

  1. Import the AppsFlyerUnityPlugin.unitypackage into your Unity project.
  2. Go to Assets >> Import Package >> Custom Package
  3. Select AppsFlyerUnityPlugin.unitypackage file.

2.3 mandatory setup for Android and iOS

Android setup

Setting the AF receiver and permissions to the AndroidManifest.xml:

<!-- receiver should be inside the <application> tag -->
<receiver android:name="com.appsflyer.MultipleInstallBroadcastReceiver" android:exported="true">
        <action android:name="com.android.vending.INSTALL_REFERRER" />
<!-- Mandatory permission: -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

Setting the Required Permissions

The AndroidManifest.xml includes the following permission:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- Optional : -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Setting the BroadcastReceiver in AndroidManifest.xml

The following two options are available for implementing the install referrer broadcast receiver:

Using a Single Broadcast ReceiverUsing a Multiple Broadcast Receiver

If you do not have a receiver listening on the INSTALL_REFERRER, in the AndroidManifest.xml, add the following receiver within the application tag:

<receiver android:name="com.appsflyer.SingleInstallBroadcastReceiver" android:exported="true">
     <action android:name="com.android.vending.INSTALL_REFERRER" />

iOS setup

Linked Frameworks and Libraries

After building the project in Unity for xCode, you must add Security.Framework to xCode's Linked Frameworks and Libraries if the framework was not added previously.

iOS Apple Search Ads

Add the following:

AppsFlyer collects IDFA only if you include this framework. Failure to add this framework means that you cannot attribute installs to Facebook, Twitter and most other ad networks.

Adding this framework to your app project is highly recommended, since it is mandatory for attributing Apple Search Ads.

3. SDK initialization

In your Start / Init methods you set the AppsFlyer dev key and the unique app IDs used by iTunes and Google Play. Note that you need to set the iOS app ID here with digits only, without the "id" prefix.

Add the following code:

Unity Plugin 4.15.1 and aboveUnity Plugin 4.14.3 and below
void Start () {
/* Mandatory - set your AppsFlyer’s Developer key. */
AppsFlyer.setAppsFlyerKey ("YOUR_APPSFLYER_DEV_KEY");
/* For detailed logging */
/* AppsFlyer.setIsDebug (true); */
  /* Mandatory - set your apple app ID
   NOTE: You should enter the number only and not the "ID" prefix */
  AppsFlyer.setAppID ("YOUR_APP_ID_HERE");
  AppsFlyer.trackAppLaunch ();
  /* Mandatory - set your Android package name */
  /* For getting the conversion data in Android, you need to add the "AppsFlyerTrackerCallbacks" listener.*/
  AppsFlyer.init ("YOUR_APPSFLYER_DEV_KEY","AppsFlyerTrackerCallbacks");


  • For Android, AppsFlyer.init includes calling trackAppLaunch. Therefore, do not call trackAppLaunch in the Android build of the Unity plugin.
  • In iOS, the conversion data response is triggered in the AppsFlyerTrackerCallbacks.cs class.

4. Recording in-app events

In-App Events provide insight on what is happening in your app. It is recommended to take the time and define the events you want to measure to allow you to measure ROI (Return on Investment) and LTV (Lifetime Value).

Recording in-app events is performed by calling trackRichEvent with event name and value parameters. See In-App Events documentation for more details.


An In-App Event name must be no longer than 45 characters. Events names with more than 45 characters do not appear in the dashboard, but only in the raw Data, Pull and Push APIs.

Recording Event Example:

System.Collections.Generic.Dictionary<string, string> purchaseEvent = new  
System.Collections.Generic.Dictionary<string, string> ();
purchaseEvent.Add ("af_currency", "USD");
purchaseEvent.Add ("af_revenue", "0.99");
purchaseEvent.Add ("af_quantity", "1");
AppsFlyer.trackRichEvent ("af_purchase", purchaseEvent);


AppsFlyer supports non-English characters with in-app events, or with any other SDK API, starting from Unity SDK version 4.15.1.

5. Performing deep linking

For deep linking, follow the instructions according to your operating system.

Add the following to your manifest file:

<activity android:name="com.appsflyer.GetDeepLinkingActivity" android:exported="true">
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <data android:scheme="your_scheme" />

To receive your deep link data, you must implement the callback onAppOpenAttribution (found in the AppsFlyerTrackerCallbacks class) that is called by the AppsFlyer SDK. It returns the Onelink/attribution link parameters used to trigger the app open. Then, you can parse the values and apply the logic to trigger the relevant app page.

public void onAppOpenAttribution(string validateResult) {
	print ("AppsFlyerTrackerCallbacks:: got onAppOpenAttribution = " + validateResult);

6. Recording revenue

Use the AFInAppEvents.REVENUE event parameter to count revenue as part of an in-app event. You can populate it with any numeric value, positive or negative.


AFInAppEvents.REVENUE(equivalent to using af_revenue) is the ONLY event parameter that is counted on AppsFlyer as real revenue on the raw data and dashboard. For more details please click here.


Revenue In-App Event
AppsFlyer.trackRichEvent(AFInAppEvents.LEVEL_ACHIEVED, new Dictionary<string, string>(){
	{AFInAppEvents.CONTENT_ID, "1234567"},
	{AFInAppEvents.CONTENT_TYPE, "category_a"},
	{AFInAppEvents.REVENUE, "1.99"},
	{AFInAppEvents.CURRENCY, "USD"}


Do NOT format the revenue value in any way. It should not contain comma separators, currency sign, or text. A revenue value should be similar to 1234.56, for example.

Recording negative revenue

If you need to record negative revenue for example when a user cancels a purchase or receives a refund, you can send negative revenue.

AppsFlyer.trackRichEvent(AFInAppEvents.PURCHASE, new Dictionary<string, string>(){
	{AFInAppEvents.CONTENT_ID, "1234567"},
	{AFInAppEvents.CONTENT_TYPE, "category_a"},
	{AFInAppEvents.REVENUE, "-1.99"},
	{AFInAppEvents.CURRENCY, "USD"}


Notice the following in the code above:

  1. The revenue value is preceded by a minus sign
  2. The event name has a unique value of "cancel_purchase" - to allow you to identify negative revenue events in the dashboard and raw data reports

7. Get conversion data

AppsFlyer allows you to access the user conversion data in real-time directly at SDK level. It enables you to customize the landing page a user views on the very first app open following a fresh app install.

To load AppsFlyer's conversion data from its servers:

  1. Add an empty GameObject
  2. Attach to it the AppsFlyerTrackerCallbacks.cs which is included in the project (you must name this gameobject AppsFlyerTrackerCallbacks). 
Android Unity Plugin > 4.15.1Android Unity Plugin < 4.14.3 iOS
/*For getting the conversion data in Android, you need to add this listener. to the init() method*/
AppsFlyer.init ("YOUR_DEV_KEY","AppsFlyerTrackerCallbacks");

In Android, you can move the methods from AppsFlyerTrackerCallbacks.cs to another class, and call that class in your listener.

You must use the exact same method namespaces that appear on AppsFlyerTrackerCallbacks.

8. User identifiers

Get AppsFlyer device ID

AppsFlyer's unique device ID is created for every new install of an app. Use the following API to obtain AppsFlyer’s Unique ID:

public String getAppsFlyerId();

Usage Example:

string AppsFlyerUID = AppsFlyer.getAppsFlyerId();

Set customer user ID

Set the User ID as used by the app.

To set the user ID, call the following method:



The customerUserID SHOULD be set before the trackAppLaunch/init. It is recommended to set your Customer User ID as soon as possible as it is only associated to events reported after its setup. Customer User ID can also be used to complete integrations with Analytics platforms such as Mixpanel and Swrve.


For iOS - Make sure to set the customer user ID each time the app is launched, before calling trackAppLaunch

For more information about the Customer User ID, click here.

Google advertising ID

From SDK Version 4.15.1 AppsFlyer automatically collects the google_advertising_id. The requirement to collect the Google Advertising ID is only relevant for SDK versions below 4.15.1.

IMEI and Android ID

By default, IMEI and Android ID are not collected by the SDK if the OS version is higher than KitKat (4.4) and the device contains Google Play Services (on Unity SDK versions 4.16.4 and below the specific app needed GPS).

To explicitly send these IDs to AppsFlyer, developers can use the following APIs:


If the app does NOT contain Google Play Services, the IMEI and Android ID are collected by the SDK. However, apps with Google play services should avoid IMEI collection as this is in violation of the Google Play policy.

Developers can opt-out of collection of IMEI and Android ID by using these APIs:



At least one device identifier, GAID, Android ID or IMEI, MUST be collected to allow for proper attribution.


AppsFlyer automatically collects the IDFA (ID For Advertisers) and IDFV (ID For Vendors) if AdSupport.framework is included in the app.

9. Optional features

Measure uninstalls

For Uninstall measurement, follow the instructions according to your operating system.

Android - FirebaseiOS
1. Download the Unity Firebase SDK from: https://firebase.google.com/docs/unity/setup.
2. Import FirebaseMessaging.unitypackage into the project.
3. Import google-services.json into the project (obtained in the Firebase console)


Manifest receivers should be automatically added by the Unity Firebase SDK.

4. In the Unity class handling the AppsFlyer code, add the following:
using Firebase.Messaging;
using Firebase.Unity;

5. Add to the Start() method:
Firebase.Messaging.FirebaseMessaging.TokenReceived += OnTokenReceived;

6. Add the following method:
public void OnTokenReceived
  (object sender, Firebase.Messaging.TokenReceivedEventArgs token) { 
    AppsFlyer.updateServerUninstallToken (token.Token);



Users who implement the Unity Firebase SDK should not add the following method call to enableUninstallTracking(“SenderID”) as the Firebase SDK will obtain the sender ID from the google-services.json file we have added earlier. Adding this method might cause a debug warning from Android.

Recording push notifications

AppsFlyer allows you to measure push notifications as part of a retargeting campaign.

handlePushNotification(Dictionary<string, string> payload)

The data payload should include an object: af with the relevant key-value string:



// with deep-linking


For more information on push notification measurement, read here.

Cross promotion attribution

AppsFlyer allows you to attribute and record installs originating from a cross promotion of one of your apps from within the current app the user has. Cross promoting apps can be a major growth factor in driving additional installs for your apps.

For details, see the Cross Promotion Attribution article, here.

User invite attribution

AppsFlyer allows you to attribute and record installs originating from user invites within your app. Allowing your existing users to invite their friends and contacts as new users to your app can be a key growth factor for your app.

For details, see the User Invite Attribution article, here.

Set currency code

You can set a global currency code using the API below, in addition to specific currency codes that can be used as part of each in-app event sent to AppsFlyer. The global currency code is used when af_currency


is not sent as part of an in-app event.

USD is the default value. You can find acceptable ISO currency codes here.

Use the following API to set the currency code:

public void setCurrencyCode(String currencyCode);

Usage Example:

setCurrencyCode(string currencyCode)

In-app purchase validation

For In-App Purchase Receipt Validation, follow the instructions according to your operating system.

Android CallCall the Listener (Android Only)iOS
//To get the callbacks
//AppsFlyer.createValidateInAppListener ("AppsFlyerTrackerCallbacks", 
"onInAppBillingSuccess", "onInAppBillingFailure"); AppsFlyer.validateReceipt(string publicKey, string purchaseData,
string signature, string price, string currency, Dictionary additionalParametes);


  • Calling validateReceipt automatically generates an af_purchase in-app event, so you don't need to send this event yourself.
  • The validate purchase response is triggered in the AppsFlyerTrackerCallbacks.cs class.

Anonymize user data

AppsFlyer provides you with a method to anonymize specific user identifiers in AppsFlyer analytics. This method complies with the latest privacy requirements and complies with Facebook data and privacy policies. Default is NO, meaning no anonymization is performed by default.

Use this API during the SDK Initialization to explicitly anonymize a user's installs, events and sessions:

public void setDeviceTrackingDisabled(boolean isDisabled);

Usage Example:

Attribution and event recording can be restarted by calling deviceTrackingDisabled again set to false.


Opting out users SEVERELY hurts your attribution information.
Use this option ONLY for regions which legally prevent you from collecting your users' information.

Custom time between sessions

By default, at least 5 seconds must lapse between 2 app launches to count as separate 2 sessions (more about counting sessions).
However, you can use the following API to set your custom value for the minimum required time between sessions:
setMinTimeBetweenSessions(int seconds)

Usage Example:


Note that setting a high value to the custom time between launches may badly impact APIs relying on sessions data, such as deep linking.

Background sessions for utility apps

Currently unavailable in Unity.

Attribute out-of-store apps


Google Play is the default store. If you are publishing your app only on Google Play, skip this section.

To record installs out of Google Play, set the channel/store at the app’s AndroidManifest.xml with a unique channel or any store name for each APK. The CHANNEL value is case sensitive.


<meta-data android:name="CHANNEL" android:value="Amazon" />
<meta-data android:name="CHANNEL" android:value="Standalone"/>
<meta-data android:name="CHANNEL" android:value="Verizon" />


You must configure the CHANNEL value at the AppsFlyer dashboard when setting up the app.

Place the meta-data tag before the </application> tag.

For more details on how to record installs for out-of-store apps, read here.


In some extreme cases you might want to shut down all SDK functions due to legal and privacy compliance. This can be achieved with the isStopTracking API. Once this API is invoked, our SDK no longer communicates with our servers and stops functioning.


In any event, the SDK can be reactivated by calling the same API, by passing false.

There are several different scenarios for user opt-out. We highly recommend following the exact instructions for the scenario, that is relevant for your app.


Use this API only in cases where you want to fully ignore this user from any and all attribution and event recording. Using this API SEVERELY impacts your attribution, data collection and deep linking mechanism.

Setting additional custom data

The setAdditionalData API is required to integrate on the SDK level with several external partner platforms, including Segment, Adobe and Urban Airship. Use this API only if the integration article of the platform specifically states setAdditionalData API is needed.
The following is a code example for implementing setAdditionalData on Unity:

Dictionary<string, string> CustomDataMap = new Dictionary<string, string>();
CustomDataMap.Add("custom_param_1", "value_of_param_1");

Attribution for pre-installed apps

Android Only

You can programmatically set a pre-installed media source, from Unity, using the following API:

setPreinstallAttribution(string MediaSource, string Campaign, string Site_Id);

For details on native implementations, click here.

Resolving Wrapped Deep Link URLs

If you are using OneLinks which support Android App Links and wrapping them with a 3rd Party Universal Link, you can use the setResolveDeepLinkURLs API to notify the AppsFlyer SDK which click domains that invoke the app should be resolved by the SDK and have the underlying OneLink extracted from them. This will allow you to maintain deep linking and attribution while wrapping the OneLink with a 3rd party Universal Link. Make sure to call this API before SDK initialization.

AppsFlyer.setResolveDeepLinkURLs("example.com", "click.example.com");


When using the AppsFlyer Unity SDK, avoid


10. Testing your integration

For instructions ton testing your integrations according to your operating system, click Android Testing or iOS Testing.

Now you can start measuring results of the media sources you work with.

11. known issues


If you are using ProGuard for Android and you encounter a warning regarding our AFKeystoreWrapperclass, then add the following code to your ProGuard rules file:

-keep class com.appsflyer.** { *; }


To exclude our SDK from the Managed bytecode stripping with IL2CPP, add the following to the link.xml:

  <assembly fullname="UnityEngine">
    <type fullname="UnityEngine.AndroidJavaRunnableProxy" preserve="all" />


If you are using additional plugins that need to override AppControllerClassName, modify AppsFlyerAppController as seen below (objective-c):

  [AppsFlyerAppController plugin];

// Singleton accessor.
+ (AppsFlyerAppController *)plugin
  static AppsFlyerAppController *sharedInstance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedInstance = [[AppsFlyerAppController alloc] init];
  return sharedInstance;


12. Unity sample project

To view a Unity sample project, click here.

Was this article helpful?
4 out of 12 found this helpful


1 comment
  • Hi Everyone,

    We are pleased to announce the release of Unity SDK v. 4.17.0.

    This unity SDK is aligned to Android SDK 4.8.13 and iOS SDK 4.8.7, and has also been updated with the following features:
    • Cross Promotion APIs
    • User Invites APIs
    • Custom Time Between Sessions
    • Pre-Install APIs

    Comment actions Permalink

Please sign in to leave a comment.