Code

Allow game maker to store player state

Overview

Here is everything needed to use the Stats feature in the "Beamable SDK for Unity".

The purpose of this feature is to allow the game maker to store player state.

Track a variety of built-in and custom player (and guild) stat variables with configurable visibility levels (i.e. visible to everyone, visible to the player, visible to the developer only, etc...).

Use Cases for Stats

  1. Data Store - A simple place to read/write info (Ex. How many characters does the player own?)
  2. Targeting - StatStat - Active data entity used for read/write of player states are the vector for player segmentation (Ex. A/B testing, targeted offer, focused message campaign, announcement for subset of player-base)

📘

Related Features

More details are covered in related feature page(s).

API

Unlike many Beamable FeatureFeature - An individual aspect of the Beamable product used to create a great user experiences, Stats does not require a specific Beamable Feature PrefabFeature Prefab - The drag-and-drop template for a specific Beamable product feature to be used. The main entry point to this feature is C# programming.

Here are API highlights for beamableAPI.StatsService.

Method Name

Detail

GetStats

Get one or more stat values

SetStats

Set one or more stat values

The SetStats and GetStats methods require additional parameters.

Parameter Name

Detail

Access

Possible values include “public” or “private”

Public client stats can be retrieved by anyone who knows your ID. Private client stats can only be retrieved for yourself. The distinction is not meaningful in backend, but in practice “game” stats are usually also “private”

Domain

Possible values include "game" (backend) or "client" (Unity)

Domain is one of “game” (backend) or “client” (Unity). Game stats can only be retrieved from microservices, but client stats can be retrieved both in microservices and in Unity code

ID

The numeric user ID of the player who owns the stats

Note: For client private stats this must match the ID of your login (e.g. beamableAPI.User.Id)

Type

Possible values include only “player”

Note: This parameter exists for legacy purposes only

Game Maker User Experience

During development, the game maker's user experience is as follows.

Steps

Follow these steps to get started.

1. Create Stats

There are no explicit steps to create a new StatStat - Active data entity used for read/write of player state. Instead, simply write to a stat via C# and if the stat does not already exist, it will be created on-the-fly.

Automatically Created Stats

The Beamable system automatically creates a specific set of game private stats for each new player. Game makers may read these values if/when its useful for the project's game design.

Stat Name

Detail

ADVERTISING_ID

The GAID or IDFA of the device that started the session (If provided)

CLIENT_VERSION

Version of the client/app which started the session (e.g. 1.0.0)

DATE_INSTALL

Timestamp of the player install (first session) expressed as unix time (milliseconds since epoch)

DATE_SESSION

Timestamp of the player's most recent session start expressed as unix time (millisecond since epoch)

DAYS_SINCE_INSTALL

Total number of days that have passed since the player installed. Or in other words, total number of days between the player's first session and most recent session

GAMER_TAG

Player's dbid/gamer tag, a unique identifier for the player in this realm

INSTALL_DATE

Date string of the player install (first session) expressed in format yyyy-MM-dd

PURCHASES_3D
PURCHASES_7D
PURCHASES_14D
PURCHASES_28D

Total number of purchases in the last X days

Note: Specifically this refers to X days preceding the most recent player session since stats are not updated when the player doesn't play

PURCHASES_TOTAL

Total number of in-app purchases, irrespective of the value of the purchases

SESSIONS_3D
SESSIONS_7D
SESSIONS_14D
SESSIONS_28D

Total number of sessions in the last X days

Note: Specifically this refers to X days preceding the most recent player session since stats are not updated when the player doesn't play

SESSIONS_TOTAL

Total number of sessions this player has started

SESSION_DAYS

The total number of days the player has played (i.e. started at least one session)

SPEND_3D
SPEND_7D
SPEND_14D
SPEND_28D

Total player spend (USD) in the last X days

Note: Specifically this refers to X days preceding the most recent player session since stats are not updated when the player doesn't play

SPEND_TOTAL

Total player spend (USD) expressed in cents

THORIUM_GAME_DEVICE

Type of device if provided

THORIUM_GAME_PLATFORM

Platform the player is playing on (e.g. Facebook, iOS)

THORIUM_GAME_SOURCE

Source of the session (If provided, e.g. "web")

TRIALS

Total list of A/B Testing trials the player is actively associated with (comma delimited list)
locale language ISO code of the player (If provided, e.g. "en")

trialmember:

Specific trial the player is a part of, with the value being the specific cohort/group the player is associated with (e.g. trialmember:button_trial = blue_button_group)

2. Use Stats

Write Stats

This writes to the stats of the current (logged in) player.

var beamableAPI = await Beamable.API.Instance;
string access = "public";
string type = "player";

Dictionary<string, string> setStats = new Dictionary<string, string>() { { "MyExampleStat", "99" } };

await beamableAPI.StatsService.SetStats(access, setStats);

Read Stats (Public Access)

This reads from the public stats of any player.

var beamableAPI = await Beamable.API.Instance;
long id = beamableAPI.User.id;
string access = "public";
string domain = "client";
string type = "player";

Dictionary<string, string> getStats = await beamableAPI.StatsService.GetStats(domain, access, type, id);

Read Stats (Private Access)

For reasons of security, reading the private stats of any player is possible only with Beamable Microservices.

See Microservices for more info.

3. View Stats

The Portal allows the game maker to view and edit player Stats.

The Beamable "Portal"The Beamable "Portal"

The Beamable "Portal"

Examples

📘

Beamable SDK Examples

This and all examples are available for download at GitHub.com/Beamable_SDK_Examples

StatBehaviour

In this StatBehaviourExample.cs example, a StatBehaviour is created and dragged into the inspector. This class derives from Unity's ScriptableObject.

This high-level solution offers high ease-of-use.

Inspector

Code

using Beamable.Stats;
using UnityEngine;

namespace Beamable.Examples.Services.StatsService
{
   /// <summary>
   /// Demonstrates <see cref="StatBehaviour"/>.
   /// </summary>
   public class StatBehaviourExample : MonoBehaviour
   {
      //  Fields  ---------------------------------------
      [SerializeField]
      private StatBehaviour _myStatBehaviour = null;

      //  Unity Methods  --------------------------------
      protected void Start()
      {
         Debug.Log($"Start()");

         //Async refresh value
         _myStatBehaviour.OnStatReceived.AddListener(MyStatBehaviour_OnStatReceived);

         // Set Value
         _myStatBehaviour.SetCurrentValue("0");
         _myStatBehaviour.SetCurrentValue("1");

         // Get Value
         Debug.Log($"_statsBehaviour.value = {_myStatBehaviour.Value}");
      }

      //  Event Handlers  -------------------------------
      private void MyStatBehaviour_OnStatReceived(string value)
      {
         // Observe Value Change
         Debug.Log($"MyStatBehaviour_OnStatReceived() value = {_myStatBehaviour.Value}");
      }
   }
}

Stat Coding

In this StatCodingExample.cs example, the C# API is used to read and write to the StatStat - Active data entity used for read/write of player state.

This low-level solution offers high flexibility.

Inspector

Code

using System.Collections.Generic;
using UnityEngine;

namespace Beamable.Examples.Services.StatsService
{
    /// <summary>
    /// Demonstrates <see cref="StatsService"/>.
    /// </summary>
    public class StatCodingExample : MonoBehaviour
    {
        //  Unity Methods  --------------------------------
        protected void Start()
        {
            Debug.Log($"Start()");

            SetupBeamable();
        }

        //  Other Methods   ------------------------------
        private async void SetupBeamable()
        {
            var beamableAPI = await Beamable.API.Instance;

            Debug.Log($"beamableAPI.User.id = {beamableAPI.User.id}");

            string statKey = "MyExampleStat";
            string access = "public";
            string domain = "client";
            string type = "player";
            long id = beamableAPI.User.id;

            // Set Value
            Dictionary<string, string> setStats =
                new Dictionary<string, string>() { { statKey, "99" } };

            await beamableAPI.StatsService.SetStats(access, setStats);

            // Get Value
            Dictionary<string, string> getStats =
                await beamableAPI.StatsService.GetStats(domain, access, type, id);

            string myExampleStatValue = "";
            getStats.TryGetValue(statKey, out myExampleStatValue);

            Debug.Log($"myExampleStatValue = {myExampleStatValue}");
        }
    }
}

Advanced

This section contains any advanced configuration options and workflows.

Analytics Events vs Stats

Beamable supports both analytics events and stats. Each use case is unique.

See Analytics » Code (Analytics Events vs Stats) for more info.

Source Value

The source value is set automatically for each Analytics events and stats.

See Analytics » Code (Source Value) for more info.


Did this page help you?