Advanced Analytics for your Unity 3D game

There’s more to mobile app success than having a reasonable strategy, an attractive UI design and solid development. In-app Analytics is key to measuring the execution and value of all the important things that happen within your app. Developers usually have access to generic numbers such as installs and activations, but those fall short of the insight needed to steer the application in the right direction and adapt the app to your users’ needs.

With Kii you get this “out-of-the-box” analytics for your application that can valuable to have a general snapshot of key metrics. You can fetch a set of predefined analytics results with no extra configuration (including user, data, file and advertising metrics) but the real power comes when you use Kii’s advanced analytics features to define custom metrics based on events or data generated by your application, with the flexibility of letting you freely define facts and dimensions.

Your metrics can be based on two data sources:

  • App Data: Object data created by your application. You can use any stored key-values for defining your custom metrics.
  • Event Data: Data thrown by your application besides application data. Kii Analytics provides you a feature to throw such event data with arbitrary key-values.

 All results will be automatically aggregated and will be ready to be presented to you.

 In this article I will show you how to work with both Event and Data based Analytics and how to fetch the Analytics processed data from the game itself  (all in the context of a simple 2D platform game demo that uses our Unity 3D SDK).

Event based Analytics

Let’s start with Event based Analytics. The mechanism is simple: you can send a custom event with custom (free form) data every time something meaningful happens in your game (eg. player dies, player reaches a special area, etc). The event data is aggregated on Kii Cloud and will be ready for slicing and dicing.

Suppose we want to send an event to the Kii Cloud every time the player dies and attaching the game time as data. The code using the Unity SDK would more or less look like this:

            // Sending Kii Analytics event for game over stats
            KiiEvent ev = KiiAnalytics.NewEvent("PlayerDeath");

            // Set key-value pairs
            ev["time"] = Time.time;
            ev["level"] = 1;

            // Upload Event Data to Kii Cloud
            KiiAnalytics.Upload(ev);

Notice that we attach the game time as if the event were a key/value store. You can attach as many dimensions as you want (all of them will be valid dimensions for slicing and dicing).

Now we need to define how to aggregate the data for visualization on the developer.kii.com and define the metrics and dimensions (for slicing and dicing). For this example we’ll call the metric “AvgDeathTime”, we make sure we select “Event Data” and select an aggegation function over the event data we sent (in this case we want to know the average of the field called “time” within the event). In Dimensions we specify the time but you could select other dimensions if they are available in your event (eg. if you pass the country in a field you could segment your analysis by country):

event_config

A step by step guide on how to configure your metric on the developer console can be found here: http://docs.kii.com/en/guides/unity/managing-analytics/flex-analytics/analyze-event-data/

After you click Save and if you already sent events ( using the source code above at least 24 hs prior to visualization) you’ll see your aggregated data:

avgdeath

Data based Analytics

Event based Analytics is powerful but has a major caveat: you need to define explicitly in your app when an event happens and which data is associated to it. That translates into app updates every time you need to define a new event/metric.

Fortunately if you’re suing Kii Cloud to store your game data you can apply the Analytics tools we described to any stored object (it doesn’t have to be an Analytics event) and, in this way, unleash the full power of Kii Analytics.

Let’s see how to store the user scores to later use data based Analytics to visualize the average user score. In order to do that you need to save an object with the score on Kii Cloud. The code will look more or less like this:

void SaveScore (int score)
{
        KiiUser user = KiiUser.CurrentUser;
        if (user == null)
            return;
        KiiBucket bucket = user.Bucket ("scores");
        KiiObject kiiObj = bucket.NewKiiObject();
        kiiObj ["score"] = score;
        kiiObj ["time"] = Time.time;
        kiiObj ["delta_time"] = Time.deltaTime;

        kiiObj.Save((KiiObject obj, Exception e) => {
            if (e != null)
                Debug.LogError(e.ToString());
            else
                Debug.Log("Score sent: " + score.ToString());
        });
 }

Notice that we also send the time together with the score. Similarly to our previous description of events, you can store any key/value combination in the object and any stored field can be used as an Analytics dimension. But unlike analytics events these objects are first class data objects and can be later retrieved with a powerful query system (among other things).

Once we sent scores this way to the back-end we can go to the developer console and configure a rule (here we’ll create one to aggregate the average user score):

user_score

Note that this rule will collect all objects with a “score” field and extract its value as an int. It will use a user scope bucket (see the source code above, you have to define the scope of bucket to store an object). Once defined we use this conversion rule to define an aggregation rule (in this case we want the average):

avg_user_score

Done! When we collect enough data we can visualize the average user score:

avg_user_score2

A full guide on how to create these rules is available here: http://docs.kii.com/en/guides/unity/managing-analytics/flex-analytics/analyze-application-data/

Fetching Analytics results inside the Game

Interestingly enough you’re not limited to visualizing event and data based analytics on the web. Some apps and games require access to some metrics to alter behaviour (eg. if the average single user score is below a certain level then game difficulty could be adjusted automatically). With the Unity SDK you can access the already processed analytics data by rule id straight from the game:

        // Define filters
        ResultCondition condition = new ResultCondition();
        condition.AddFilter("AppVersion", "9");
        condition.AddFilter("level", 1);
        condition.GroupingKey = "level";
        condition.DateRange = new DateRange(new DateTime(2014, 2, 23), 
                              new DateTime(2014, 2, 25));
        try
        {
            GroupedResult result = KiiAnalytics.GetResult("143", condition);
            IList<GroupedSnapShot> snapshots = result.SnapShots;
            foreach (GroupedSnapShot snapshot in snapshots)
            {
                // do something with snapshot.Data
            }
        }
        catch (Exception e)
        {
            errText = e.Message;
        }

Note that we initially define a condition to filter on the analytics results (of which it’s important to define a date range). The condition also allows to define a grouping key for the results (similar to a SQL group_by). Then we pass the condition and a rule ID to fetch the analytics results (which will be returned in snapshots containing data in json format). You’ll have to parse the json data into the appropriate format (depending on what kind of rule data you’re working with).

That’s all for now. We hope you can try out Kii Analytics in your game to get the necessary insight to improve the player experience. You might want to try out the demo described in this article which is available here:

https://github.com/KiiPlatform/Kii2DPlatformer