Introducing a New Multi-platform SDK from Segment - Analytics for .NET and Unity

Segment Analytics' new SDK for .NET and Unity simplifies integration of user behavior tracking and data analysis. The SDK collects data from various sources, supports real-time data streaming, and integrates with other analytics and marketing tools.

By Michael Grosse Huelsewiesche

Analytics Everywhere, Business or Pleasure

The Mobile SDK team here at Segment is excited to introduce Analytics-CSharp, a new SDK for use in .NET, Xamarin, and Unity. Several customers reached out about their desire for a well-supported analytics solution for their games and applications in the Unity 3d engine. We took the opportunity to modernize our support for Xamarin and .NET at the same time since Unity supports .NET Standard 2.0. As a result, we now have a single library with first class support across three platforms!

The new Analytics-CSharp SDK is available on Nuget, the standard package manager for .NET and Xamarin. In order to best support Unity, it’s also available through a popular third-party repository, OpenUPM. In all cases, it’s quick and easy to install directly from your IDE or with a simple CLI command. No manipulating of files or tweaking linker settings required!

A Modern SDK

To modernize our old .NET and Xamarin SDKs, we focused on the following areas: interface and performance.

The new SDK implements the same plugin architecture used by our next-generation libraries to provide a higher level of extensibility and flexibility. All of our SDKs feature destination plugins to channel analytics data directly from a mobile device to the many available data consumers such as Mixpanel. Our latest SDKs expand on this architecture by defining new plugin interfaces that can act at different points in the information pipeline. This allows you to write simple classes that could, for example, transform values to match a previous version or filter events before they are sent to your destinations. This can streamline how you instrument your application, limit excessive data, and match formatting for various services. 

We have also made improvements to performance, both in terms of thread management and operations per minute. Our new threading library minimizes performance impacts to your application by handling analytics processing and communication in the background. We’ve also focused on reducing the overhead of processing events and lowering CPU usage. Our new Analytics library will have a minimal impact on the battery life of mobile devices, which in turn leads to more game play.

Using the New SDK

Let’s walk through adding Analytics to an Application. We’ll demo Unity’s Dragon Crashers UI Toolkit sample, but the changes here will be the same on any .NET platform, whether it’s Xamarin or a server application.


Starting the Project

After creating an empty project, add the Dragon Crashers sample from Unity’s asset store. The import will overwrite your project with the sample’s resources. After it completes, try out the game, buy armor, and fight a dragon!


Now you have a running game, but wouldn’t you like to know more about your player’s experience and what leads them to make a purchase? You can analyze this data and more with a variety of enterprise-level tools from across the entire industry. That’s where Segment comes in.

Adding Segment Analytics

To get started with Analytics, we’ll need a Unity Source in our segment dashboard. Once you’ve found it in the catalog and added it to your workspace, the Source Overview page will provide you with a block of sample init code that includes the very important Write Key. You can follow installation instructions from the Unity Source page, or if you already use OpenUPM, you can run a single CLI command from your project folder: 

openupm add

We’ll have a single static instance of our Analytics object, so let’s add it to the GameDataManager, found here: Assets/Scripts/Managers/GameDataManager.cs Include Segment.Analytics with the following using statement:

using System;
using UnityEngine.SceneManagement;
using Segment.Analytics;

namespace UIToolkitDemo

Add our static member variable:

SaveManager m_SaveManager;
bool m_IsGameDataInitialized;
public static Analytics analytics;

void OnEnable()

Then we need to initialize it at the beginning of the existing Start method. Here we set flushAt = 1 and flushInterval = 10, so we can see events available on Segment dashboard immediately right after it’s tracked. In production, we want to configure these parameters to a larger number to preserve battery.

void Start()
    var configuration = new Configuration("Your WriteKey",
        flushAt: 1,
        flushInterval: 10);
    analytics = new Analytics(configuration);

Now we want to add Analytics.Track calls wherever something happens that you want to track. Let’s get data on what people are purchasing in the store:

void OnPurchaseItem(ShopItemSO shopItem, Vector2 screenPos)
    if (shopItem == null)

    // invoke transaction succeeded or failed
    if (HasSufficientFunds(shopItem))
        TransactionProcessed?.Invoke(shopItem, screenPos);
        analytics.Track("Purchase", new JsonObject
          ["item_name"] = shopItem.itemName,
          ["cost"] = shopItem.cost

As you can see, it’s easy to add detailed information using a new JsonObject. This allows more convenient types than C#’s dictionary type, but if your application already uses them they can be passed in as well.

First Results

We can already see some activity in the Debugger tab of your Unity source in the Segment dashboard:

Expanding Tracking

There’s some important information we don’t want to miss out on - Who is making these purchases? To find out, let’s add an Identify call to the welcome message pop-up. We’ll just enter the username, but additional properties can be specified to include email addresses or data like birthdays for handling account recovery.

void ShowWelcomeMessage()
    string message = "Welcome " + "<color=#" + PopUpText.TextHighlight + ">" + GameData.username + "</color>!";

This won’t just record the user’s login, but will also associate their tracking data across sessions, so use a unique identifier such as UUID if you can. In this sample app we only have a username for demonstration purposes. If no identity info is available then an anonymous identifier will be used instead. You can still get great data even if your app doesn’t require a login.

Here you can see the anonymous ID that was generated when the game started and was initialized with an empty string, as well as the name afterward:


You might also want to know when the user looks at the store page. This type of data can help analyze the path they take through your app. For that we’ll use an Analytics.Screen call in another file, Assets/Scripts/UI/Controllers/ShopController.cs:

void LoadShopData()
    // load the ScriptableObjects from the Resources directory (default = Resources/GameData/MailMessages)

Additional information can be supplied in this call with a dictionary or a JsonObject. For example, if your app dynamically generates the list of shop items, you can record what the player saw before making a purchase.

From here you can add instrumentation to any in-game event that you might find interesting. You can record milestones like complete levels and boss kills, or player set-back events like deaths or item drops, and even correlate them all to your customer’s behavior and engagement.

Beginning your Analytics Journey

Using Segment, you can not only do analysis on all of this data, but also automatically take action to engage your players! How about a push campaign based on the user’s progress in the game? Did the player get beaten by a boss and then not log on for a week? How might they respond to a gloating message from the enemy, or a helpful offer of items from a friendly character? 

What’s more, you get the inherited benefits from Segment’s cloud destination. Do you analyze your data in BigQuery? No problem, we can automatically sync that from Segment to BigQuery. Do you use MixPanel for analytics? Segment will automatically forward your Segment events to your Mixpanel account. 

I hope this article has inspired some ideas about how enterprise analytics can help you understand your customers.  When you’re ready to take the next steps, there are plenty of resources from Segment to help guide you. Here are a few: 

Test drive Segment

Test drive Segment CDP today

It’s free to connect your data sources and destinations to the Segment CDP. Use one API to collect analytics data across any platform.

Recommended articles


Want to keep updated on Segment launches, events, and updates?