Record user actions with Analytics events

Tutorial

Beginner

+10XP

30 mins

Unity Technologies

Record user actions with Analytics events

In this tutorial, you’ll learn how to use standard and custom events to record user actions and view the data of those actions on the Unity Dashboard.

1. Overview

The Analytics package collects data about events, which are notifications triggered by user actions within your games. Standard events, including launching the game or watching an ad, are generated automatically by the Analytics package. Custom events, such as the player completing a level, must be implemented in code. Custom events are great for answering specific questions about your game and seeing how a design decision plays out.

Important: You must define custom events and their parameters before sending them from your game because Analytics validates every event as it’s received. Any events that don’t meet the definition in your Event Manager will be rejected, which ensures that your dataset isn’t polluted with rogue events.

In this tutorial, you’ll prepare a simple scene so you can start sending events, and you’ll configure your own custom event.

2. Initialize the Analytics SDK

The Analytics software development kit (SDK) needs to be initialized before your app will send any events to the Dashboard.

To add a script to initialize the Analytics SDK when your scene loads, follow these instructions :

1. Open the project you previously linked to the Analytics Dashboard.

2. Create a new scene or use an existing one.

3. Right-click in the Hierarchy window and select Create Empty to create an empty GameObject that will act as a container for your analytics script.

4. Rename the GameObject “UGS_Analytics”.

5. Create a new script and add it to the UGS_Analytics GameObject.

6. Open the script and replace the contents with the following lines of code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Services.Analytics;
using Unity.Services.Core;
using Unity.Services.Core.Analytics;
using UnityEngine.UnityConsent;




public class UGS_Analytics : MonoBehaviour
{
    async void Start()
    {
            await UnityServices.InitializeAsync();
            GiveConsent(); //Get user consent according to various legislations
    }


    public void GiveConsent()
    {
        // Call if consent has been given by the user
        EndUserConsent.SetConsentState(new ConsentState
        {
             AnalyticsIntent = ConsentStatus.Granted,
        });
        Debug.Log($"Consent has been provided. The SDK is now collecting data!");
    }


}

This script will use an asynchronous task to attempt to initialize the Analytics SDK and wait for a response.

Important: The example in the code above is only meant to be used to provide consent and test sending a custom event, quickly. You might need to seek player consent before recording Analytics events. The Analytics SDK documentation contains more information on Data Privacy and Consent.

You’re now ready to run the game and send your first Analytics events.

For more information on using Analytics in code, check out the Analytics documentation and Unity Gaming Services Sample Project

3. Enable Debug event reporting

By default, the Analytics SDK doesn’t log information about Analytics Events in the Editor’s Console window, to ensure that the SDK runs as efficiently as possible. However, you might want to enable logging for extra visibility while you experiment.

To view the debug messages for every event sent in the Console window, follow these instructions:

1. In the Unity Editor, from the main menu, select Edit > Project Settings.

2. In the Project Settings window, select the Player section.

3. In the Player section, use the foldout (triangle) to expand the Other Settings section.

4. In the Script Compilation section, select Scripting Define Symbols.

5. Select the Add to the list (+) button.

6. Add the keyword “UNITY_ANALYTICS_EVENT_LOGS”.

7. Select the Apply button.

Define debug Symbols

Note: It’s advisable to remove logging before you build your app for release.

4. Send a standard Analytics event

Some standard events like gameStarted and clientDevice are automatically sent just by installing and initializing the SDK then running your game. Even though your app doesn’t do anything yet, you can generate these events.

To send a standard Analytics event, follow this instruction:

1. In the Unity Editor, enter Play mode.

Since you have enabled debugging in the previous step, you’ll see some log messages in the Console window.

Unity Editor console log showing standard events recorded.

Standard events provide information to help you to determine the number of players in your game, session counts, duration, retention, demographics, and device information. For a complete list of standard events, check out the Events list in the Unity Manual.

5. Validate your events

Validating your events confirms that they’re being sent correctly from your project and received by Unity Analytics before you rely on them for reporting or decision-making. To validate your events and see how these events appear in Analytics, follow these instructions:1. Return to the Unity Dashboard and select your project.

2. Select Services > Analytics, then select Launch.

3. In the Analytics view, select Event Browser.

Note: It can take up to 15 minutes before events appear in the Event Browser.

If your events don't appear here, make sure that you have consented to collecting analytics for the device you’re using.

Event browser with standard events listed.

The Event Browser provides a quick way to check that your events are recorded and passing validation. If for any reason your events fail validation, you’ll be able to see the precise reasons on the Invalid Events tab. You’ll learn more about debugging and handling invalid events in the next tutorial.

For more information about the Event Browser, check out the Event Browser page of the Unity Manual.

6. Create a custom event

While standard events provide you with some important basic information, we recommend using custom events to further understand how players experience your game.

Custom events record specific player actions that you identify in your game. A custom event should describe a meaningful player action in the game and reveal details of the action and player state at that time.

In the following steps, you’ll create a custom event named levelCompleted. When a player completes a certain level of your game, this event will capture their progress.

To create a custom event, follow these instructions:

1. Go to Unity dashboard.unity.com, then select Analytics > Event Manager.

2. Select Add New > Custom Event.

Event Manager, showing menu to add a new custom event.

3. Rename the custom event “levelCompleted”.

4. Enter “The levelCompleted event is triggered if a player successfully completed a level” in the Event description box.

5. Enable Enable event (optional).

The Add Custom Event window with the levelCompleted Event name and Event description field filled in.

6. Select the Confirm button.

You’ve successfully created the levelCompleted custom event, which defines a clear, meaningful player action and establishes the foundation for tracking player progress in Analytics.

7. Create a custom parameter

Parameters are attached to events to reveal details of the action and player state at that time the event occurs.

Next, you’ll add the levelName parameter to the levelCompleted event to record which level is completed. From that information, you can see if there are particular levels that users are struggling with.

You can also create your own parameters in this levelCompleted event to provide more context about the player’s state at that time, such as timeOnLevel, coinBalance, powerLevel, levelDuration, and bulletsFired.

Tip: It’s better to record occasional, richly detailed, and meaningful events than a stream of sparse events.

To add a levelName parameter to the levelCompleted event, follow these instructions:

1. In the Event Manager, select the levelCompleted event.

2. Select the Assign Parameter button.

3. Select the Parameter box, select Add New Parameter, name it “levelName”, and add “This parameter identifies which level was completed, allowing you to analyze player progression and difficulty across levels” in the Parameter description box..

4. Open the Parameter type dropdown and select String.

Note: levelName is stored as a String because level identifiers are typically text-based (for example, "Level_1" or "DungeonBoss"), rather than numeric values.

5. Select the Create button.

The Add Custom Parameter window with details filled in.

Important: You can’t change a parameter’s data type once it has started to receive data. Be sure to choose the parameter type most appropriate to the data you are sending. Parameters may have String, Integer, Float, or Boolean data types.

Note: You can reach out to our support team to request a change to the parameter data type.

8. Assign a custom parameter to a custom event

Creating a custom parameter and assigning it to a custom event can all be done in the same flow. You must assign the parameter to a custom event so that the event will pass validation.

To assign your custom parameter to your custom event, follow these instructions:

1. While still in the levelCompleted custom event from the previous steps, locate the newly created levelName parameter in the +Assign Parameter list.

2. Enable levelName.

Assign Parameter list showing the levelName parameter checkbox enabled.

3. Select Confirm to finalize the Custom Event creation.

The Add Custom Event  view of the Dashboard.

Once you’ve created your event, click on the levelCompleted event, your event Schema will open. It includes your custom event in the eventParams list.

Event Schema for level.

9. Send a custom event

To start sending in the newly created custom event with its respective parameters, you must update the script added to the UGS_Analytics GameObject.

To demonstrate the levelCompleted event with the levelName parameter, you’ll need to update your script to call the custom event when you load the scene. For now, a random level will be registered on each load to mimic the user playing different levels.

To update and test the script, follow these instructions:

1. Open the script attached to the UGS_Analytics GameObject.

2. Update the script to match the following script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Services.Analytics;
using Unity.Services.Core;
using Unity.Services.Core.Analytics;
using UnityEngine.UnityConsent;


public class UGS_Analytics : MonoBehaviour
{
    async void Start()
    {
            await UnityServices.InitializeAsync();
            GiveConsent(); //Get user consent according to various legislations
            LevelCompletedCustomEvent();
    }


    private void LevelCompletedCustomEvent()
    {
        int currentLevel = Random.Range(1, 4); //Gets a random number from 1-3


        //Define Custom Parameters
        CustomEvent myEvent = new CustomEvent("levelCompleted")
        	{
            	{ "levelName", "level" + currentLevel.ToString()}
        	};


        //The ‘levelCompleted’ event will get cached locally
        //and sent during the next scheduled upload, within 1 minute
        AnalyticsService.Instance.RecordEvent(myEvent);


        // You can call Events.Flush() to send the event immediately
        AnalyticsService.Instance.Flush();
    }


    public void GiveConsent()
    {
        // Call if consent has been given by the user
        EndUserConsent.SetConsentState(new ConsentState
        {
             AnalyticsIntent = ConsentStatus.Granted,
        });
        Debug.Log($"Consent has been provided. The SDK is now collecting data!");
    }


}

3. Observe the Console window logs and see your events uploaded to the servers.

Console logs for levelCompleted.

Note: A “Dispatcher is already flushing” warning message may appear; however, for the purpose of this tutorial that’s okay. Remove the AnalyticsService.Instance.Flush(); line if the events are being recorded and uploaded appropriately.

4. On the Dashboard, go to the Event browser to see those events listed.

Event Schema for levelCompleted

5. Expand the event by selecting the <> button and see the value passed for the levelName parameter.

For more information about recording custom events, check out the Create Custom Events page and The CustomEvent Class page of the Unity Manual.

10. Next steps

You’ve created your own custom event that now appears on your Unity Dashboard. Next, you’ll learn more about how to access, manage, and visualize this data on the Unity Dashboard and set up your own data reports.

Complete this Tutorial