Skip to main content

GameAnalyticsHandler

A class that allows you to easily track events, resources, and progressions in your game using GameAnalytics.

Types

GameAnalyticsPlayerIdentifier

type GameAnalyticsPlayerIdentifier = Player | Model | number | string | nil

Player to track the event for. (Player, Character, userId, Username, nil)

If it is nil, it will be treated as the "Game / Server"

GameAnalyticsProgressionStatus

type GameAnalyticsProgressionStatus = "Start" | "Complete" | "Fail"

Enum for progression status required for ProgressionEvents

Functions

new

static
GameAnalyticsHandler.new(Params{
BuildVersionstring,
Resources{string},
Currencies{string},
GameKeystring,
SecretKeystring,
AutomaticSendBusinessEventsboolean?,
TrackPerformanceboolean?,
EnabledInfoLogboolean?,
EnabledVerboseLogboolean?,
EnabledReportErrorsboolean?,
SuppressWarningsboolean?,
SendEventsToGAFromStudioboolean?,
SendEventsPredicate(() → boolean)?
}) → ()

The constructor for the GameAnalyticsHandler. Creates a new instance of the GameAnalyticsHandler where you can track events, resources, and progressions in your game using GameAnalytics.

[REQUIRED]

  • BuildVersion -> The version of the game. Example: "0.0.1"
  • Resources -> The resources to track in the game. Example: {"Wheel Spin", "Chest", "Daily Rewards"}
  • Currencies -> The currencies to track in the game. Example: {"Coins", "Gems", "Diamonds"}
  • GameKey -> The Game Key provided by GameAnalytics.
  • SecretKey -> The Secret Key provided by GameAnalytics.

[OPTIONAL]

  • AutomaticSendBusinessEvents -> Automatically send business events to GameAnalytics. Default: true
  • TrackPerformance -> Track performance of the server and clients. Default: true
  • EnabledInfoLog -> Enable info logs. Default: true
  • EnabledVerboseLog -> Enable verbose logs. Default: true
  • EnabledReportErrors -> Enable error reporting. Default: true
  • SuppressWarnings -> Suppress warnings. Default: false
  • SendEventsToGAFromStudio -> Send events to GameAnalytics from studio. Default: false
  • SendEventsPredicate -> A predicate function to determine if events should be sent to GameAnalytics. Default: (()-> true)

Example Usage

local gaParams = {
    BuildVersion = "0.0.1",
    Resources = {"Wheel Spin", "Chest", "Daily Rewards"},
    Currencies = {"Coins", "Gems", "Diamonds"},
    GameKey = ServerStorage.GameAnalyticsSettings.GameKey.Value,
    SecretKey = ServerStorage.GameAnalyticsSettings.SecretKey.Value,
}

local gaClass = GameAnalyticsHandler.new(gaParams)

AddDesignEvent

GameAnalyticsHandler:AddDesignEvent(designParams{
eventIdstring,
valuenumber
}) → ()

Design Events are used to track player interactions in the game. They are custom events that allow tracking different actions or behaviors within a game. These events can be used to monitor game mechanics and understand player behavior in a detailed way. The eventId is a unique identifier used to categorize and track specific design events. It is formatted as "Label1:Label2:Label3:Label4:Label5" to provide structured and hiearchical way of organizing these events.

  • identifier -> The player to track the event for.
  • eventId -> The event id to track. Example: "Killed:Nuketown:MP5" Tracking Killed event on what map with what gun
  • value -> The value to track for the event. Example: 1 for "Killed:Nuketown:MP5" would be 1 kill.
EventId category limits

EventIds can have at max 5 labels (categories), and at minimum 1 label. Ex: "Label1:Label2:Label3:Label4:Label5"

Example Usage

-- Tracking how many kills a player got with which gun and on which map.
local playerKills: {[Player]: number} = {}

-- increment players kills, and report the event to GameAnalytics.
local function plrGotKill(player: Player, playerWhoGotKilled: Player, mapName: string, gunName: string)
    if not playerKills[player] then
        playerKills[player] = 0
    end

    playerKills[player] += 1

    gaClass:AddDesignEvent({
        identifier = player,
        eventId = `Killed:{mapName}:{gunName}`,
        value = 1
    })
end

plrGotKill(game.Players.KinqAndi, game.Players.builderman, "Nuketown", "MP5")

AddResourceEvent

GameAnalyticsHandler:AddResourceEvent(resourceParams{
currencyNamestring,
beforenumber,
afternumber,
itemTypestring,
itemIdstring
}) → ()

Resource Events are used to track the flow of resources in the game such as currency. These events can be used to monitor the economy of the game and understand how players interact with the resources in the game. Helping understand how players acquire and spend their in-game resources.

  • identifier -> The player to track the event for.
  • currencyName -> The currency name to track. Example: "Coins"
  • before -> The amount of currency before the event. Example 200
  • after -> The amount of currency after the event. Example 100
  • itemType -> The itemType of the resource. Example: "Chest"
  • itemId -> The itemId of the resource. There are no restrictions on this field. Example: "Gold"
Field Restrictions

The 'currencyName' parameter must be defined in the class constructor Params as an item of Currencies. The 'itemType' parameter must be defined in the class constructor Params as an item of Resources.

Example Usage

-- In this example, we are tracking the player's resource event. The player had 200 coins before and 50 coins after buying a gold chest.
local playersCoins: {[Player]: number} = {}

--increments the player's amount of a specific currency
local function incrementCurrency(player: Player, currencyName: string, currencyAmount: number, itemType: string, itemId: string)
    if not playersCoins[player] then
        playersCoins[player] = 200
    end

    local beforeIncrement: number =  playersCoins[player]
    local afterIncrement: number = beforeIncrement + currencyAmount

    playersCoins[player] = afterIncrement

    gaClass:AddResourceEvent({
        identifier = player,
        currencyName = currencyName,
        before = beforeIncrement,
        after = afterIncrement,
        itemType = itemType,
        itemId = itemId
    })
end

--decrements the player's amount of a specific currency
local function decrementCurrency(player: Player, currencyName: string, currencyAmount: number)
    incrementCurrency(player, currencyName, -currencyAmount)
end

--opens a chest
local chestCosts = {["Gold"] = 150, ["Silver"] = 25, ["Bronze"] = 10}

--open a chest up for player
local function openChest(player: Player, chestId: string)
    if playersCoins[player] and playersCoins[player] > chestCosts[chestId] then
        decrementCurrency(player, "Coins", -chestCosts[chestId], "Chest", chestId)

        -- grant rewards
    end
end

AddProgressionEvent

GameAnalyticsHandler:AddProgressionEvent(progressionParams{
progressionStatusGameAnalyticsProgressionStatus,
progression01string,
progression02string?,
progression03string?,
scorenumber
}) → ()

Progression events are used to track player's progress through different stages, levels, or milestones within a game. These events help understand how players are advancing, where they might be getting stuck, and how they are interacting with the game's progression system.

  • identifier -> The player to track the event for.
  • progressionStatus -> GameAnalyticsProgressionStatus enum values. ("Start", "Complete", "Fail").
  • progression01 -> Defines the category of the progression. Example: "World1"
  • progression02 -> Defines the sub-category of the progression. Example: "WeaponLeveled"
  • progression03 -> Defines the sub-sub-category of the progressio. Example: "Sword3"
  • score -> Defines the score of the progression. Example: 10
info

Out of the keys (progression01, progression02, progression03), only progression01 is required.

Example Usage

local playerWeapons: {[Player]: {
    [string]: {[string]: number}
}} = {}

--tracks the player's weapon level progression
local function levelWeapon(player: Player, worldName: string, weaponName: string, level: number)
    -- handle table defaults
    playerWeapons[player] = playerWeapons[player] or {}
    playerWeapons[player][worldName] = playerWeapons[player][worldName] or {}
    playerWeapons[player][worldName][weaponName] = playerWeapons[player][worldName][weaponName] or 1


    local previousLevel: number = playerWeapons[player][worldName][weaponName]
    playerWeapons[player][worldName][weaponName] = level

    gaClass:AddProgressionEvent({
        identifier = player,
        progressionStatus = "Complete",
        progression01 = "WeaponLeveled",
        progression02 = worldName,
        progression03 = weaponName,
        score = level
    })
end

-- In this example, we are tracking the player's progression in the game. The player has leveled Sword3 to 10 in World1.
levelWeapon(game.Players.KinqAndi, "Nuketown", "MP5", 5)

ProcessReceiptCallback

GameAnalyticsHandler:ProcessReceiptCallback(info{
PurchaseIdnumber,
PlayerIdnumber,
ProductIdnumber,
PlaceIdWherePurchasednumber,
CurrencySpentnumber,
CurrencyTypeEnum.CurrencyType
}) → ()

Reporting a purchase event to GameAnalytics. This is used to track developer product purchases made in the game.

info

The info parameter should be the receiptInfo provided by MarketplaceService.ProcessReceipt.

Example Usage

MarketplaceService.ProcessReceipt = function(receiptInfo)
    gaClass:ProcessReceiptCallback(receiptInfo)
    --grant developer product rewards
end

GetDefaultSetting

GameAnalyticsHandler:GetDefaultSetting(settingNamestring) → any

Get a default setting of the constructor parameters.

Example Usage

local automaticSendBusinessEvents = gaClass:GetDefaultSetting("AutomaticSendBusinessEvents")
print(automaticSendBusinessEvents) -- true

Destroy

GameAnalyticsHandler:Destroy() → ()

Destroys the game analytics class and clears all connections.

Show raw api
{
    "functions": [
        {
            "name": "new",
            "desc": "The constructor for the GameAnalyticsHandler. Creates a new instance of the GameAnalyticsHandler where you can track events, resources, and progressions in your game using GameAnalytics.\n\n[**REQUIRED**]\n- `BuildVersion` -> The version of the game. Example: \"0.0.1\"\n- `Resources` -> The resources to track in the game. `Example: {\"Wheel Spin\", \"Chest\", \"Daily Rewards\"}`\n- `Currencies` -> The currencies to track in the game. `Example: {\"Coins\", \"Gems\", \"Diamonds\"}`\n- `GameKey` -> The Game Key provided by GameAnalytics.\n- `SecretKey` -> The Secret Key provided by GameAnalytics. \n\n[**OPTIONAL**]\n- `AutomaticSendBusinessEvents` -> Automatically send business events to GameAnalytics. `Default: true`\n- `TrackPerformance` -> Track performance of the server and clients. `Default: true`\n- `EnabledInfoLog` -> Enable info logs. `Default: true`\n- `EnabledVerboseLog` -> Enable verbose logs. `Default: true`\n- `EnabledReportErrors` -> Enable error reporting. `Default: true`\n- `SuppressWarnings` -> Suppress warnings. `Default: false`\n- `SendEventsToGAFromStudio` -> Send events to GameAnalytics from studio. `Default: false`\n- `SendEventsPredicate` -> A predicate function to determine if events should be sent to GameAnalytics. `Default: (()-> true)`\n\n\nExample Usage\n```lua\nlocal gaParams = {\n    BuildVersion = \"0.0.1\",\n    Resources = {\"Wheel Spin\", \"Chest\", \"Daily Rewards\"},\n    Currencies = {\"Coins\", \"Gems\", \"Diamonds\"},\n    GameKey = ServerStorage.GameAnalyticsSettings.GameKey.Value,\n    SecretKey = ServerStorage.GameAnalyticsSettings.SecretKey.Value,\n}\n\nlocal gaClass = GameAnalyticsHandler.new(gaParams)\n```",
            "params": [
                {
                    "name": "Params",
                    "desc": "",
                    "lua_type": "{\n        BuildVersion: string,\n        Resources: {string},\n        Currencies: {string},\n        GameKey: string,\n        SecretKey: string,\n\n        AutomaticSendBusinessEvents: boolean?,\n        TrackPerformance: boolean?,\n        EnabledInfoLog: boolean?,\n        EnabledVerboseLog: boolean?,\n        EnabledReportErrors: boolean?,\n        SuppressWarnings: boolean?,\n        SendEventsToGAFromStudio: boolean?,\n        SendEventsPredicate: (()-> boolean)?\n    }"
                }
            ],
            "returns": [],
            "function_type": "static",
            "tags": [
                "static"
            ],
            "source": {
                "line": 117,
                "path": "src/gameanalyticshandler/src/Shared/GameAnalyticsHandler/Server.lua"
            }
        },
        {
            "name": "AddDesignEvent",
            "desc": "Design Events are used to track player interactions in the game. They are custom events that allow tracking different actions or behaviors within a game. These events can be used to monitor game mechanics and understand player behavior in a detailed way.\nThe eventId is a unique identifier used to categorize and track specific design events. It is formatted as \"Label1:Label2:Label3:Label4:Label5\" to provide structured and hiearchical way of organizing these events.\n\n- `identifier` -> The player to track the event for.\n- `eventId` -> The event id to track. Example: \"Killed:Nuketown:MP5\" Tracking Killed event on what map with what gun\n- `value` -> The value to track for the event. Example: 1 for \"Killed:Nuketown:MP5\" would be 1 kill.\n\n:::warning EventId category limits\nEventIds can have at max 5 labels (categories), and at minimum 1 label.\nEx: `\"Label1:Label2:Label3:Label4:Label5\"`\n:::\n\nExample Usage\n```lua\n-- Tracking how many kills a player got with which gun and on which map.\nlocal playerKills: {[Player]: number} = {}\n\n-- increment players kills, and report the event to GameAnalytics.\nlocal function plrGotKill(player: Player, playerWhoGotKilled: Player, mapName: string, gunName: string)\n    if not playerKills[player] then\n        playerKills[player] = 0\n    end\n\n    playerKills[player] += 1\n\n    gaClass:AddDesignEvent({\n        identifier = player,\n        eventId = `Killed:{mapName}:{gunName}`,\n        value = 1\n    })\nend\n\nplrGotKill(game.Players.KinqAndi, game.Players.builderman, \"Nuketown\", \"MP5\")\n```",
            "params": [
                {
                    "name": "designParams",
                    "desc": "",
                    "lua_type": "{\n        identifier: GameAnalyticsPlayerIdentifier?,\n        eventId: string,\n        value: number\n    }"
                }
            ],
            "returns": [],
            "function_type": "method",
            "source": {
                "line": 242,
                "path": "src/gameanalyticshandler/src/Shared/GameAnalyticsHandler/Server.lua"
            }
        },
        {
            "name": "AddResourceEvent",
            "desc": "Resource Events are used to track the flow of resources in the game such as currency.\nThese events can be used to monitor the economy of the game and understand how players interact with the resources in the game.\nHelping understand how players acquire and spend their in-game resources.\n\n- `identifier` -> The player to track the event for.\n- `currencyName` -> The currency name to track. `Example: \"Coins\"`\n- `before` -> The amount of currency before the event. `Example 200`\n- `after` -> The amount of currency after the event. `Example 100`\n- `itemType` -> The itemType of the resource. `Example: \"Chest\"`\n- `itemId` -> The itemId of the resource. There are no restrictions on this field. `Example: \"Gold\"`\n\n:::warning Field Restrictions\nThe 'currencyName' parameter must be defined in the class constructor Params as an item of Currencies.\nThe 'itemType' parameter must be defined in the class constructor Params as an item of Resources.\n:::\n\nExample Usage\n```lua\n-- In this example, we are tracking the player's resource event. The player had 200 coins before and 50 coins after buying a gold chest.\nlocal playersCoins: {[Player]: number} = {}\n\n--increments the player's amount of a specific currency\nlocal function incrementCurrency(player: Player, currencyName: string, currencyAmount: number, itemType: string, itemId: string)\n    if not playersCoins[player] then\n        playersCoins[player] = 200\n    end\n\n    local beforeIncrement: number =  playersCoins[player]\n    local afterIncrement: number = beforeIncrement + currencyAmount\n\n    playersCoins[player] = afterIncrement\n\n    gaClass:AddResourceEvent({\n        identifier = player,\n        currencyName = currencyName,\n        before = beforeIncrement,\n        after = afterIncrement,\n        itemType = itemType,\n        itemId = itemId\n    })\nend\n\n--decrements the player's amount of a specific currency\nlocal function decrementCurrency(player: Player, currencyName: string, currencyAmount: number)\n    incrementCurrency(player, currencyName, -currencyAmount)\nend\n\n--opens a chest\nlocal chestCosts = {[\"Gold\"] = 150, [\"Silver\"] = 25, [\"Bronze\"] = 10}\n\n--open a chest up for player\nlocal function openChest(player: Player, chestId: string)\n    if playersCoins[player] and playersCoins[player] > chestCosts[chestId] then\n        decrementCurrency(player, \"Coins\", -chestCosts[chestId], \"Chest\", chestId)\n\n        -- grant rewards\n    end\nend\n```",
            "params": [
                {
                    "name": "resourceParams",
                    "desc": "",
                    "lua_type": "{\n        identifier: GameAnalyticsPlayerIdentifier,\n        currencyName: string,\n        before: number,\n        after: number,\n        itemType: string,\n        itemId: string\n    }"
                }
            ],
            "returns": [],
            "function_type": "method",
            "source": {
                "line": 347,
                "path": "src/gameanalyticshandler/src/Shared/GameAnalyticsHandler/Server.lua"
            }
        },
        {
            "name": "AddProgressionEvent",
            "desc": "Progression events are used to track player's progress through different stages, levels, or milestones within a game.\nThese events help understand how players are advancing, where they might be getting stuck, and how they are interacting with the game's progression system.\n\n- `identifier` -> The player to track the event for.\n- `progressionStatus` -> GameAnalyticsProgressionStatus enum values. (\"Start\", \"Complete\", \"Fail\").\n- `progression01` -> Defines the category of the progression. `Example: \"World1\"`\n- `progression02` -> Defines the sub-category of the progression. `Example: \"WeaponLeveled\"`\n- `progression03` -> Defines the sub-sub-category of the progressio. `Example: \"Sword3\"`\n- `score` -> Defines the score of the progression. `Example: 10`\n\n:::info\nOut of the keys (progression01, progression02, progression03), only progression01 is required.\n:::\n\nExample Usage\n```lua\nlocal playerWeapons: {[Player]: {\n    [string]: {[string]: number}\n}} = {}\n\n--tracks the player's weapon level progression\nlocal function levelWeapon(player: Player, worldName: string, weaponName: string, level: number)\n    -- handle table defaults\n    playerWeapons[player] = playerWeapons[player] or {}\n    playerWeapons[player][worldName] = playerWeapons[player][worldName] or {}\n    playerWeapons[player][worldName][weaponName] = playerWeapons[player][worldName][weaponName] or 1\n\n\n    local previousLevel: number = playerWeapons[player][worldName][weaponName]\n    playerWeapons[player][worldName][weaponName] = level\n\n    gaClass:AddProgressionEvent({\n        identifier = player,\n        progressionStatus = \"Complete\",\n        progression01 = \"WeaponLeveled\",\n        progression02 = worldName,\n        progression03 = weaponName,\n        score = level\n    })\nend\n\n-- In this example, we are tracking the player's progression in the game. The player has leveled Sword3 to 10 in World1.\nlevelWeapon(game.Players.KinqAndi, \"Nuketown\", \"MP5\", 5)\n```",
            "params": [
                {
                    "name": "progressionParams",
                    "desc": "",
                    "lua_type": "{\n        identifier: GameAnalyticsPlayerIdentifier,\n        progressionStatus: GameAnalyticsProgressionStatus,\n        progression01: string,\n        progression02: string?,\n        progression03: string?,\n        score: number\n    }"
                }
            ],
            "returns": [],
            "function_type": "method",
            "source": {
                "line": 467,
                "path": "src/gameanalyticshandler/src/Shared/GameAnalyticsHandler/Server.lua"
            }
        },
        {
            "name": "ProcessReceiptCallback",
            "desc": "Reporting a purchase event to GameAnalytics. This is used to track developer product purchases made in the game.\n\n:::info\nThe info parameter should be the receiptInfo provided by MarketplaceService.ProcessReceipt.\n:::\n\nExample Usage\n```lua\nMarketplaceService.ProcessReceipt = function(receiptInfo)\n    gaClass:ProcessReceiptCallback(receiptInfo)\n    --grant developer product rewards\nend\n```",
            "params": [
                {
                    "name": "info",
                    "desc": "",
                    "lua_type": "{\n    PurchaseId: number,\n    PlayerId: number,\n    ProductId: number,\n    PlaceIdWherePurchased: number,\n    CurrencySpent: number,\n    CurrencyType: Enum.CurrencyType\n}"
                }
            ],
            "returns": [],
            "function_type": "method",
            "source": {
                "line": 537,
                "path": "src/gameanalyticshandler/src/Shared/GameAnalyticsHandler/Server.lua"
            }
        },
        {
            "name": "GetDefaultSetting",
            "desc": "Get a default setting of the constructor parameters.\n\nExample Usage\n```lua\nlocal automaticSendBusinessEvents = gaClass:GetDefaultSetting(\"AutomaticSendBusinessEvents\")\nprint(automaticSendBusinessEvents) -- true\n```",
            "params": [
                {
                    "name": "settingName",
                    "desc": "",
                    "lua_type": "string"
                }
            ],
            "returns": [
                {
                    "desc": "",
                    "lua_type": "any\n"
                }
            ],
            "function_type": "method",
            "source": {
                "line": 580,
                "path": "src/gameanalyticshandler/src/Shared/GameAnalyticsHandler/Server.lua"
            }
        },
        {
            "name": "Destroy",
            "desc": "Destroys the game analytics class and clears all connections.",
            "params": [],
            "returns": [],
            "function_type": "method",
            "source": {
                "line": 592,
                "path": "src/gameanalyticshandler/src/Shared/GameAnalyticsHandler/Server.lua"
            }
        }
    ],
    "properties": [],
    "types": [
        {
            "name": "GameAnalyticsPlayerIdentifier",
            "desc": "Player to track the event for. (Player, Character, userId, Username, nil)\n\nIf it is nil, it will be treated as the \"Game / Server\"",
            "lua_type": "Player | Model | number | string | nil",
            "source": {
                "line": 32,
                "path": "src/gameanalyticshandler/src/Shared/GameAnalyticsHandler/Server.lua"
            }
        },
        {
            "name": "GameAnalyticsProgressionStatus",
            "desc": "Enum for progression status required for ProgressionEvents",
            "lua_type": "\"Start\" | \"Complete\" | \"Fail\"",
            "source": {
                "line": 39,
                "path": "src/gameanalyticshandler/src/Shared/GameAnalyticsHandler/Server.lua"
            }
        }
    ],
    "name": "GameAnalyticsHandler",
    "desc": "A class that allows you to easily track events, resources, and progressions in your game using GameAnalytics.",
    "source": {
        "line": 12,
        "path": "src/gameanalyticshandler/src/Shared/GameAnalyticsHandler/Server.lua"
    }
}