Custom Game Analytics System Part 1
Quantitative Overview
We are going to build a custom analytics system (this example uses Unity, but it can easily be reconfigured to any other platform so long as you can send HTTP requests).
We want to get the data from our events there into BigQuery. BigQuery is essentially a place to store data. Think of it like a giant database we can run SQL queries on and fetch the data from.
Now you can have Unity and BigQuery connect directly; however, it is much more fiddly and honestly is a pain to set up, as there are many more levels of authentication and permissions to try and get set up.
So a much easier way is to use an Apps Script as a middleman. Apps Script has much easier authentication and setup so it’s what we’ll use. It’s essentially like a Google permission pop-up we see everywhere now.
Once we have the data populating BigQuery tables, we will then use Data Studio (formerly Looker Studio) to display that in a custom dashboard that can be shared with anyone and made as easy to interpret for everyone on the team.
Now it may look like I work for Google, but no. I have found that their workspace and cloud suite has pretty much everything needed in one place and with one account, rather than needing different tools from different providers with different subscriptions.
And I’m sure most devs use Google Workspace. That said, everything here is possible using a basic free Google account.

You can preview the end result in Data Studio here
Defining the data to track
What data to track? That really depends on the game…
For Grove Keeper — a stats-heavy game — we are tracking quite a lot of different things that the player does at different moments in the game. Currently, we have 8 different analytics events, each with dozens of parameters.
For a basic game, you may need only a few events. I’ll run through setting up some basics that should cover most games
Session Start Event
- Event Name
- User ID
- User Machine Specs
- Users Location
- Date of Start
Level Start Event
- Event Name
- Level Name
- Level Difficulty
Level Finished Event
- Event Name
- Level Name
- Level Difficulty
- Status: Won, Lost
- Score
- Time
1. Unity code and event set-up
With the events defined, it is now time to set up the code in Unity. The AnalyticsSender should not require any modifications, as you can enter the variable values in the inspector. The AnalyticsManager and Example are showing you how to then create the events and get them sent to the AnalyticsSender.
AnalyticsSender.cs
The AnalyticsSender is the core script that does all the hard work. It should not need any modifications. The main things that you will need to add in the inspector are the endpoint and the secretToken.
The flush threshold governs how often to send the data to BigQuery. When an event gets sent to the AnalyticsSender, it gets put in a queue. Once the queue count reaches the flush threshold, it will send the data. The reason to add to a queue is so that we can batch-send the data to Apps Script in a single insert request. The more insert requests sent, the more of your quota it eats up.
The core class here is the AnalyticsEvent class, which all events will extend from. This has the minimum required variables.
[System.Serializable]
public class AnalyticsEvent
{
public string event_name;
public string user_id;
public string timestamp;
}
Note that the variables are using snake_case since that is the convention used in most web systems. The code is commented pretty well, so it should explain everything
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using Newtonsoft.Json;
/// <summary>
/// The Analytics Sender is responsible for sending the data/payloads to Big Query.
/// The code in here should not need to be changed.
/// </summary>
public class AnalyticsSender : MonoBehaviour
{
#region Variables
[Tooltip("endPoint will be something like: https://script.google.com/macros/s/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/exec")]
[SerializeField] private string endpoint = "";
[Tooltip("secretToken can be whatever you want (eg a GUID), but must be the same as the SECRET_TOKEN in the Apps Script")]
[SerializeField] private string secretToken = "";
[Tooltip("Safety net: auto-flush after this many queued events (guards against crashes mid-session)")]
[SerializeField] private int flushThreshold = 10;
[Tooltip("Max seconds to wait for the flush request before allowing quit anyway")]
[SerializeField] private int quitTimeoutSeconds = 5;
[Tooltip("When true, analytics are sent when running in the editor")]
[SerializeField] private bool sendFromEditor = false;
[Tooltip("When true, analytics are sent in builds (uncheck to suppress all build sends)")]
[SerializeField] private bool sendFromBuild = true;
private bool ShouldSend => Application.isEditor ? sendFromEditor : sendFromBuild;
private readonly List<AnalyticsEvent> queue = new();
private bool quitting;
#endregion
#region Public Functions
/// <summary>
/// Adds an analytics event to the queue.
/// If we reach the flushThreshold, then flush the event queue
/// </summary>
public void AddAnalyticsEvent(AnalyticsEvent _event)
{
queue.Add(_event);
if (queue.Count >= flushThreshold)
FlushEvents();
}
/// <summary>
/// Can be called at any time to flush the Analytics Event Queue
/// </summary>
public void FlushEvents()
{
if (queue.Count == 0) return;
var batch = new List<AnalyticsEvent>(queue);
queue.Clear();
if (!ShouldSend)
return;
StartCoroutine(SendBatchRoutine(batch, _timeout: 30));
}
#endregion
#region Private Functions
/// <summary>
/// Sends the events via a POST web request to the endpoint of our AppsScript
/// </summary>
private IEnumerator SendBatchRoutine(List<AnalyticsEvent> _events, int _timeout, System.Action _onComplete = null)
{
//Turn the events list into a payload to convert to json
var payload = new BatchPayload { token = secretToken, events = _events };
string json = JsonConvert.SerializeObject(payload);
byte[] body = Encoding.UTF8.GetBytes(json);
using UnityWebRequest req = new UnityWebRequest(endpoint, "POST");
req.uploadHandler = new UploadHandlerRaw(body);
req.downloadHandler = new DownloadHandlerBuffer();
req.SetRequestHeader("Content-Type", "application/json");
req.timeout = _timeout;
yield return req.SendWebRequest();
if (req.result != UnityWebRequest.Result.Success)
Debug.LogError($"Analytics batch failed ({_events.Count} events): {req.error}\n{req.downloadHandler.text}");
else
Debug.Log($"Analytics batch sent: {_events.Count} events | {req.downloadHandler.text}");
_onComplete?.Invoke();
}
/// <summary>
/// We want to ensure that the events send when we quit
/// As the SendBatchRoutine can take some time, we want to ensure they send before the application closes
/// </summary>
private bool OnWantsToQuit()
{
// Nothing queued, or already flushing, or shouldn't send — allow quit
if (queue.Count == 0 || quitting || !ShouldSend)
return true;
// Intercept the quit, flush, then re-trigger quit when done
quitting = true;
var batch = new List<AnalyticsEvent>(queue);
queue.Clear();
//Start the send and then quit once it has completed
StartCoroutine(SendBatchRoutine(batch, _timeout: quitTimeoutSeconds, _onComplete: Application.Quit));
return false;
}
#endregion
#region Events & Classes
private void OnEnable() => Application.wantsToQuit += OnWantsToQuit;
private void OnDisable() => Application.wantsToQuit -= OnWantsToQuit;
/// <summary>
/// Class to hold the batch of events so they can be sent together
/// </summary>
private class BatchPayload
{
public string token;
public List<AnalyticsEvent> events;
}
#endregion
}
#region Classes
/// <summary>
/// The core events class that all events will inherit from
/// Every event needs these to correctly reconcile in BigQuery & Data Studio
/// </summary>
[System.Serializable]
public class AnalyticsEvent
{
public string event_name;
public string user_id;
public string timestamp;
}
#endregion
AnalyticsManager.cs
This is an example of an AnalyticsManager, in which we are creating classes for all the events we want to track, and functions that can be called from other scripts to then send the data to the AnalyticsSender. Make your own version of this appropriate to what you want to track. Note that you can move to your own namespace.
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using UnityEngine;
using Random = UnityEngine.Random;
namespace BV.Analytics.Examples
{
/// <summary>
/// The AnalyticsManager is where we write the game specific events we want to use.
/// Other scripts should call an event in here, which then gets sent to the AnalyticsSender.
/// Create your own copy and modify to your needs.
/// Your version does not need to be in the BV.Analytics namespace
/// </summary>
public class AnalyticsManager : MonoBehaviour
{
#region Variables
[SerializeField] private AnalyticsSender analyticsSender;
[Tooltip("Add other machine ids here to exclude")] [SerializeField]
private List<string> excludeThese;
// Machines in excludeThese (e.g. dev/test rigs) are excluded from the send so their play doesn't skew analytics.
// excludeSelf excludes the machine running right now without needing to know its id.
private bool IsExcludedDevice => excludeThese != null && excludeThese.Contains(DeviceID);
private string DeviceID => SystemInfo.deviceUniqueIdentifier;
private string Now => DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
private bool trackingFPS;
private int fpsFrameCount;
private float levelStartTime;
#endregion
#region Unity Functions
private void Awake()
{
SetSessionStarted();
}
private void Update()
{
if (trackingFPS)
fpsFrameCount++;
}
#endregion
#region Analytics Events
/// <summary>
/// Will run once only when a player starts up the game
/// </summary>
private void SetSessionStarted()
{
AddEvent(new SessionStartedEvent
{
event_name = "session_started",
user_id = DeviceID,
timestamp = Now,
os = SystemInfo.operatingSystem,
cpu = SystemInfo.processorType,
cpu_cores = SystemInfo.processorCount,
gpu = SystemInfo.graphicsDeviceName,
ram_mb = SystemInfo.systemMemorySize,
vram_mb = SystemInfo.graphicsMemorySize,
language = CultureInfo.CurrentUICulture.Name,
country = new RegionInfo(CultureInfo.CurrentCulture.Name).TwoLetterISORegionName
});
}
/// <summary>
/// Run when a level starts. Add in whatever parameters needed.
/// </summary>
public void SetLevelStarted(string _levelName, int _levelNumber, string _difficulty)
{
trackingFPS = true;
levelStartTime = Time.realtimeSinceStartup;
fpsFrameCount = 0;
AddEvent(new LevelStartedEvent
{
event_name = "level_started",
user_id = DeviceID,
timestamp = Now,
level_name = _levelName,
level_number = _levelNumber,
level_difficulty = _difficulty,
});
}
/// <summary>
/// Run when a level ends. Add in whatever parameters needed.
/// </summary>
public void SetLevelFinished(string _levelName, int _levelNumber, string _levelResult, string _difficulty,
int _score, int _deaths, List<EnemyStats> _enemies)
{
trackingFPS = false;
//Below is the actual way to get the time elapsed between level start and finish.
//However, I have added a random version just for testing otherwise all level time values were too low
//float levelElapsed = Time.realtimeSinceStartup - levelStartTime;
float levelElapsed = Random.Range(10, 100);
float avgFPS = levelElapsed > 0f ? fpsFrameCount / levelElapsed : 0f;
AddEvent(new LevelFinishedEvent
{
event_name = "level_finished",
user_id = DeviceID,
timestamp = Now,
level_name = _levelName,
level_number = _levelNumber,
level_result = _levelResult,
level_difficulty = _difficulty,
level_time_seconds = Mathf.RoundToInt(levelElapsed),
avg_fps = Mathf.RoundToInt(avgFPS),
score = _score,
deaths = _deaths,
// Serialize the nested list to a JSON string so it fits the STRING column in BigQuery.
// Query it in BigQuery with JSON_EXTRACT / JSON_VALUE.
enemy_stats = JsonConvert.SerializeObject(_enemies),
});
}
/// <summary>
/// Single entry point for every event to the AnalyticsSender. Excluded machines never get added.
/// </summary>
private void AddEvent(AnalyticsEvent _event)
{
if (IsExcludedDevice)
return;
analyticsSender.AddAnalyticsEvent(_event);
}
/// <summary>
/// Sends all the events that have been placed in the senders queue
/// </summary>
public void FlushEvents() => analyticsSender.FlushEvents();
#endregion
}
#region Event Classes
/// <summary>
/// Classes to hold the event data
/// They all extend the base AnalyticsEvent class in the Analytics Sender
/// Generally only basic data types (string, int, float, bool)
/// Using a web-based naming convention for the variable names (snake_case)
/// These variable names are what you use in BigQuery tables and should be named exactly the same
/// </summary>
[Serializable]
public class SessionStartedEvent : AnalyticsEvent
{
public string os;
public string cpu;
public int cpu_cores;
public string gpu;
public int ram_mb;
public int vram_mb;
public string language;
public string country;
}
[Serializable]
public class LevelStartedEvent : AnalyticsEvent
{
public string level_name;
public int level_number;
public string level_difficulty;
}
[Serializable]
public class LevelFinishedEvent : AnalyticsEvent
{
public string level_name;
public int level_number;
public string level_result;
public string level_difficulty;
public int level_time_seconds;
public int avg_fps;
public int score;
public int deaths;
public string enemy_stats;
}
#endregion
}
AnalyticsEventsExample.cs
This is an example script that shows where you could capture the data, then send it off to the AnalyticsManager to then send to the AnalyticsSender.
using UnityEngine;
using System.Collections.Generic;
namespace BV.Analytics.Examples
{
/// <summary>
/// Shows Examples of calling an analytics event.
/// You can have one master class that all other scripts talk to send the events (like this one),
/// or have the other scripts directly call the AnalyticsManager making this script redundant
/// Your version does not need to be in the BV.Analytics namespace
/// </summary>
public class AnalyticsEventsExample : MonoBehaviour
{
[SerializeField] private AnalyticsManager analyticsManager;
[Header("Dummy Data")]
[SerializeField] private string[] levelResult = { "Won", "Lost", "Quit" };
[SerializeField] private string[] levelNames = { "Water World", "Fire Land", "Ironwood" };
[SerializeField] private string[] levelDifficulty = { "Easy", "Medium", "Hard" };
public void SetLevelStarted()
{
int rnd = Random.Range(0, levelNames.Length - 1);
analyticsManager.SetLevelStarted(levelNames[rnd], rnd, levelDifficulty[rnd]);
}
public void SetLevelFinished()
{
int rnd = Random.Range(0, levelNames.Length - 1);
int rndScore = Random.Range(0, 1000);
int rndDeaths = Random.Range(0, 5);
List<EnemyStats> enemyStats = new List<EnemyStats>();
enemyStats.Add(new EnemyStats { enemyType = "Dwarf", killedAmount = Random.Range(0, 20) });
enemyStats.Add(new EnemyStats { enemyType = "Warrior", killedAmount = Random.Range(0, 20) });
enemyStats.Add(new EnemyStats { enemyType = "Wizard", killedAmount = Random.Range(0, 20) });
analyticsManager.SetLevelFinished(levelNames[rnd], rnd, levelResult[rnd], levelDifficulty[rnd], rndScore,
rndDeaths, enemyStats);
}
public void FlushAllEvents() => analyticsManager.FlushEvents();
}
//A class to hold some enemy stats.
//Shows pushing data into the events that will convert to json.
[System.Serializable]
public class EnemyStats
{
public string enemyType;
public int killedAmount;
}
}
Connect it all in Unity
I generally create a GameObject and call it AnalyticsManager. I put all three scripts on it (Sender first, then Manager, then the Example). Here is where you can change variables as needed.
In the demo, I have just hooked up each event from the example script (LevelStartedEvent, LevelFinishedEvent) to UI buttons that will fire the event when clicked. If you try to run an event now, it will fail as we still need to get our Endpoint and Secret Token. These will come after you complete the next steps.

2. BigQuery Setup
BigQuery is used as our database. It is essentially a place to dump all our event data. We can view the data here and run SQL queries like any other database. In our case though, we are purely going to use it to store data, not for viewing.
Create the BigQuery project
- Go to console.cloud.google.com and create a new project.
- Open the project, then go to BigQuery from the menu.
- Click on Datasets, then create a dataset.
- Ensure your Project ID is the one you just created.
- Choose the Data location closest to you.
- Make note of this, as you will need to use the same Data location for all future connections.
Create the BigQuery tables
- In the BigQuery dataset, go to Create Table
- Leave ‘Create table From’ as Empty Table.
- Name the table the same as the event name from the data we want to track
- eg. session_started
- Table type: Native table
- Under Schema, click on Add Field
- Fill in the Field name with the name of the data we are tracking from our event, and change the type appropriately (we pretty much use just STRING and INTEGER for everything except for the TIMESTAMP.
- Once filled out, click the Create table button at the bottom
- Create new tables for the other events you want to track in the same way.
That’s all for BigQuery for now. We will come back to it once we have some data propagating.
3. Apps Script Setup
Now we can get Unity to connect directly to BigQuery, but it is a pain in the ass. There are many more levels of authentication needed, security setups and several techy steps that can be a pain to troubleshoot.
It’s much easier to use Apps Script as a middleman. It already has a BigQuery connector built in, so all we need to do is use a Google Sign-In request, and it all works as intended. It is still secure so long as you don’t share your SECRET_TOKEN and other variables with others.
- Go to script.google.com
- Create a New Project and name it appropriately.
- Copy the code below and replace the following variables and their values (replace xxxxxx with your values):
- var SECRET_TOKEN = “xxxxxxx”; // Can be anything you want. e.g. use a GUID generator
var PROJECT_ID = “xxxxxxx”; // The project ID from BigQuery
var DATASET_ID = “xxxxxxx”; // The dataset ID from BigQuery (Where your tables live)
- var SECRET_TOKEN = “xxxxxxx”; // Can be anything you want. e.g. use a GUID generator
- Ctrl+S to save.
- Go to Services + on the side.
- Select BigQuery API, set to V2 and click Add.
- Click on the Deploy button and change these in the pop-up:
- New Description: Whatever you like
- Execute as: Me
- Who has access: Anyone
- Click the Deploy button
- Click the Authorise access button.
- Choose the account and accept all permissions
- Copy the Web app URL somewhere, as we’ll use this in Unity.
- Copy the SECRET_TOKEN somewhere, as we’ll also use this in Unity.
- Click the Run button to make sure everything is working.
var SECRET_TOKEN = "xxxxxxx"; // Can be anything you want. e.g. a GUID
var PROJECT_ID = "xxxxxxx"; // The project ID from BigQuery
var DATASET_ID = "xxxxxxx"; // The dataset ID from BigQuery (Where your tables live)
function doPost(e) {
try {
var payload = JSON.parse(e.postData.contents);
// Reject requests that don't know the secret
if (payload.token !== SECRET_TOKEN) {
return ContentService.createTextOutput("unauthorized");
}
var events = payload.events;
if (!events || !Array.isArray(events) || events.length === 0) {
return ContentService.createTextOutput("no_events");
}
// Group rows by their target table (event_name)
var grouped = {};
events.forEach(function(event) {
var table = event.event_name;
if (!table) return;
if (!grouped[table]) grouped[table] = [];
grouped[table].push({
insertId: Utilities.getUuid(),
json: event
});
});
// One insertAll call per table — all rows land in one round trip
Object.keys(grouped).forEach(function(tableName) {
BigQuery.Tabledata.insertAll(
{
rows: grouped[tableName],
ignoreUnknownValues: true
},
PROJECT_ID,
DATASET_ID,
tableName
);
});
return ContentService.createTextOutput("ok");
}
catch(err) {
return ContentService.createTextOutput("error: " + err.message);
}
}
function triggerAuth() {
BigQuery.Projects.list();
}
4. Back to Unity
Connect it all up in Unity
I generally create a GameObject and call it AnalyticsManager. I put all three scripts on it (Sender first, then Manager, then the Example). Here is where you can change variables as needed.
- Get the Web app URL that you copied from your Apps Script and put it into the Endpoint variable slot.
- Get the SECRET_TOKEN from your Apps Script and put it in the Secret Token variable slot.
In the demo, I have just hooked up each event from the example script (LevelStartedEvent, LevelFinishedEvent) to UI buttons that will fire the event when clicked.
Run the game now, and once you reach the flush threshold (or manually flush the events), you should see a success message in the console. Woo hoo!

5. Check the data in BigQuery
Now that we have successfully sent an event, it is time to check the results in BigQuery.
- Go to your BigQuery dataset
- Click on an event (eg. session_started)
- Add a * between SELECT and FROM (this is a wildcard/all, so it just means select all from the table). Here is an example of how it would look, but the bv-game-analytics… would be your data.
- SELECT * FROM `bv-game-analytics-example.bv_game_analytics_example_data.session_started` LIMIT 1000
- Click the Run button
- You should see data from your table
- You can optionally save this query using the Save button next to Run.
- Repeat for the other events to ensure their data has come across.
- Winner!

