Installing the Library

This library can be installed using the unity package manager system with git. We support Unity 2018.3 and above. For older versions of Unity, you need to have .NET 4.x Equivalent selected as the scripting runtime version in your editor settings.

  • In your unity project root open ./Packages/manifest.json
  • Add the following line to the dependencies section "com.mixpanel.unity": "https://github.com/mixpanel/mixpanel-unity.git#master",
  • Open Unity and the package should download automatically
    Alternatively you can go to the releases page and download the .unitypackage file and have unity install that.

Initializing the Library

To start tracking with the Mixpanel Unity library, you must first initialize it with your project token. You can find your token by clicking your name in the upper righthand corner of your Mixpanel project and selecting Settings from the dropdown.

Configuring Mixpanel

To initialize the library, first open the unity project settings menu for Mixpanel. (Edit -> Project Settings -> Mixpanel) Then, enter your project token into the Token and Debug Token input fields within the inspector.

📘

NOTE

You have the option to provide different tokens for debug and production builds of your project. Keeping data sets separate is important to maintain the integrity of the metrics you’re tracking with Mixpanel. It’s very easy to prevent these data sets from commingling, but hard to disentangle, so taking time up front is well worth it. First, create two separate Mixpanel projects – a "Production" project and a "Debug" project (Mixpanel doesn’t limit the number of projects you can use). Then, you can enter your "Production" and "Debug" project tokens into the Token and Debug Token input fields respectively.

C Sharp

Once you've initialized the library with your project token, you can import Mixpanel into your code using the mixpanel namespace.

using mixpanel;

// Then, you can track events with
Mixpanel.Track("Plan Selected");

Sending your First Event

Once you've initialized the library, you can track an event using Mixpanel.Track() with the event name and properties.

var props = new Value();
props["Gender"] = "Female";
props["Plan"] = "Premium";

Mixpanel.Track("Plan Selected", props);

Flushing Events

To preserve battery life and customer bandwidth, the Mixpanel library doesn't send the events you record immediately. Instead, it sends batches to the Mixpanel servers periodically while your application is running. On Unity, you can configure the interval at which data is flushed to Mixpanel. The default time is that data gets flushed every 60 seconds.

Timing Events

You can track the time it took for an action to occur, such as an image upload or a comment post, using Mixpanel.StartTimedEvent This will mark the "start" of your action, which you can then finish with a track call. The time duration is then recorded in the "Duration" property.

Mixpanel.StartTimedEvent("Image Upload");

Mixpanel.Track("Image Upload");

Super Properties

It's very common to have certain properties that you want to include with each event you send. Generally, these are things you know about the user rather than about a specific event—for example, the user's age, gender, or source.

To make things easier, you can register these properties as super properties. If you do, we will automatically include them with all tracked events. Super properties are saved to device storage, and will persist across invocations of your app.

To set super properties, call Mixpanel.Register.

// Send a "User Type: Paid" property will be sent
// with all future track calls.
Mixpanel.Register("User Type", "Paid");

Going forward, whenever you track an event, super properties will be included as properties. For instance, if you call

var props = new Value();
props["signup_button"] = "test12";

Mixpanel.Track("signup", props);

after making the above call to Mixpanel.Register, it is just like adding the properties directly:

var props = new Value();
props["signup_button"] = "test12";
props["User Type"] = "Paid";

Mixpanel.Track("signup", props);

Setting Super Properties Only Once

If you want to store a super property only once (often for things like ad campaign or source), you can use Mixpanel.RegisterOnce. This function behaves like Mixpanel.Register and has the same interface, but it doesn't override super properties you've already saved.

Mixpanel.RegisterOnce("source", "ad-01");

This means that it's safe to call Mixpanel.RegisterOnce with the same property on every app load, and it will only set it if the super property doesn't exist.

Super Properties Live in Local Storage

Mixpanel's server-side libraries do not automatically append "super properties" to their events. You are more than welcome to roll your own system to append whatever properties you'd like to events for a given user. The most important thing to note when dealing with appending properties server side is that you must include a value for the (traditionally super) property "distinct_id" in order to use the events in most Mixpanel reports. The distinct_id property ties an event to a specific user.

Managing User Identity

You can handle the identity of a user using the identify and alias methods. Proper use of these methods can connect events to the correct user as they move across devices, browsers, and other platforms.

Identify

Identify a user with a unique ID to track user activity across devices, tie a user to their events, and create a user profile. If you never call this method, unique visitors are tracked using a UUID that generates the first time they visit the site.

Argument

Type

Description

unique_id

String
optional

A string that uniquely identifies a user - we recommend a user id. If not provided, the distinct_id currently in the persistent store (cookie or localStorage) is used.

Call identify when you know the identity of the current user, typically after log-in or sign-up. We recommend against using identify for anonymous visitors to your site.

// Associate all future events sent from
// the library with the distinct_id 13793
Mixpanel.Identify('13793');

📘

ID Merge

If a project has ID Merge enabled, the identify method will connect pre- and post-authentication events when appropriate.

If a project does not have ID Merge enabled, identify will change the user's local distinct_id to the unique ID you pass. Events tracked prior to authentication will not be connected to the same user identity. If ID Merge is disabled, alias can be used to connect pre and post registration events.

Alias

The alias method creates an alias which Mixpanel will use to remap one id to another. Multiple aliases can point to the same identifier.

Argument

Type

Description

alias

String
required

A unique identifier that you want to use as an identifier for this user.

distinct_id

String
optional

The current user identifier.

The following is a valid use of alias:

Mixpanel.Alias("13793");

Aliases can also be chained. You cannot point to multiple identifiers.

❗️

ID Merge

If a project does not have ID Merge enabled, the best practice is to call alias once when a unique ID is first created for a user (e.g., when a user first registers for an account). Do not use alias multiple times for a single user without ID Merge enabled.

Call Reset at Logout

Reset generates a new random distinct_id and clears super properties. Call reset to clear data attributed to a user when that user logs out. This allows you to handle multiple users on a single device. For more information about maintaining user identity, see the Identity Management: Best Practices article.

Storing User Profiles

In addition to events, you can store user profiles in Mixpanel's User Analytics product. Profiles are persistent sets of properties that describe a user—things like name, email address, and signup date. You can use profiles to explore and segment users by who they are, rather than what they did. You can also use profiles to send messages, such as emails, SMS, or push notifications.

📘

NOTE

Before you send profile updates, you must call Mixpanel.Identify. This ensures that you only have registered users saved in the system.

Setting Profile Properties

You can set properties on a user profile with Mixpanel.people.Set.

// mixpanel identify: must be called before
// user profile properties can be set
Mixpanel.Identify("13793");

// Sets user 13793's "Plan" attribute to "Premium"
Mixpanel.People.Set("Plan", "Premium");

This will set a "Plan" property, with a value "Premium," on user 13793's profile. If there isn't a profile with distinct_id 13793 in Mixpanel already, a new profile will be created. If user 13793 already has a property named "Plan" in their profile, the old value will be overwritten with "Premium."

📘

NOTE

Pick your property names wisely. Once you've sent them to Mixpanel, there is no way to change them. Feel free to use capitalization and spaces in between words.
There are a few limitations:

  • Your property names should not begin with $ or mp_. These properties are reserved for special properties sent by Mixpanel.
  • Your property names cannot begin or end with a space as they will automatically be trimmed.
  • Your property names and values cannot be longer than 255 characters. In practice they should be much shorter than that. Property names get cut off by our user interface at about 20 characters.

Click here to see a list of Mixpanel's reserved user profile properties.

Incrementing Numeric Properties

You can use Mixpanel.people.Increment to change the current value of numeric properties. This is useful when you want to keep a running tally of things, such as games played, messages sent, or points earned.

// Here we increment the user's point count by 500.
Mixpanel.People.Increment("point count", 500);

Other Types of Profile Updates

There are a few other types of profile updates. To learn more, please see the full API reference.

Tracking Revenue

Mixpanel makes it easy to analyze the revenue you earn from individual customers. By associating charges with user profiles, you can compare revenue across different customer segments and calculate things like lifetime value.

You can track a single transaction with Mixpanel.people.TrackCharge. This call will add transactions to the individual user profile, which will also be reflected in the Mixpanel Revenue report.

// Make sure identify has been called before making revenue
// updates
Mixpanel.Identify("13793");

// Tracks $100 in revenue for user 13793
Mixpanel.People.TrackCharge(100);

// Refund this user 50 dollars
Mixpanel.People.TrackCharge(-50);

// Tracks $25 in revenue for user 13793 on the 2nd of
// January
var props = new Value();
props["time"] = "2012-01-02T00:00:00";

Mixpanel.People.TrackCharge(25, props);

Registering for Push Notifications

The Mixpanel library includes support for sending iOS push notification device tokens to Mixpanel. Once you send a device token, you can use Mixpanel to send push notifications to your app.

📘

NOTE

Android push notifications are not supported through this Mixpanel library or through the Unity Notification Services class.

You can send a device token to Mixpanel from the Unity NotificationServices.RegisterForNotifications class, using Mixpanel.people.PushDeviceToken.

using UnityEngine;
using System.Collections;
using NotificationServices = UnityEngine.iOS.NotificationServices;
using NotificationType = UnityEngine.iOS.NotificationType;
using mixpanel;

public class NotificationRegistrationExample : MonoBehaviour {
  bool tokenSent;

  void Start() {
    tokenSent = false;

    NotificationServices.RegisterForNotifications(
    NotificationType.Alert |
    NotificationType.Badge |
    NotificationType.Sound);
  }

  void Update () {
    if (!tokenSent) {
      byte[] token = NotificationServices.deviceToken;
      if (token != null) {

        // Make sure identify has been called
        // before sending a device token.
        Mixpanel.Identify("13793");

        // This sends the deviceToken to Mixpanel
        #if UNITY_IOS
          Mixpanel.People.PushDeviceToken = token;
        #endif

        tokenSent = true;
      }
    }
  }
}

Updated 27 days ago

Unity


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.