### GroupsService Example Setup
Source: https://docs.beamable.com/docs/groups-code
Sets up the Beamable context and subscribes to GroupsService and ChatService changes. This example demonstrates how to observe group and chat events, create chat rooms for groups, and manage group data.
```csharp
using System.Collections.Generic;
using System.Threading.Tasks;
using Beamable.Common.Api;
using Beamable.Common.Api.Groups;
using UnityEngine;
using Beamable.Experimental.Api.Chat;
using UnityEngine.Events;
namespace Beamable.Examples.Services.GroupsService
{
///
/// Holds data for use in the .
///
[System.Serializable]
public class GroupsServiceExampleData
{
public List GroupNames = new List();
public List GroupPlayerNames = new List();
public List RoomNames = new List();
public List RoomPlayerNames = new List();
public List RoomMessages = new List();
public string GroupToCreateName = "";
public bool IsInGroup = false;
public bool IsInRoom = false;
public string MessageToSend = "";
}
[System.Serializable]
public class RefreshedUnityEvent : UnityEvent { }
///
/// Demonstrates .
///
public class GroupsServiceExample : MonoBehaviour
{
// Events ---------------------------------------
[HideInInspector]
public RefreshedUnityEvent OnRefreshed = new RefreshedUnityEvent();
// Fields ---------------------------------------
private ChatView _chatView = null;
private GroupsView _groupsView = null;
private BeamContext _beamContext;
private ChatService _chatService;
private GroupsServiceExampleData _data = new GroupsServiceExampleData();
// Unity Methods --------------------------------
private async void Start()
{
Debug.Log("Start()")
await SetupBeamable();
}
// Methods --------------------------------------
private async Task SetupBeamable()
{
_beamContext = await BeamContext.Default.Instance;
_chatService = _beamContext.ServiceProvider.GetService();
Debug.Log($"beamContext.UserId = {_beamContext.UserId}");
// Observe GroupsService Changes
_beamContext.Api.GroupsService.Subscribe(async groupsView =>
{
_groupsView = groupsView;
_data.IsInGroup = _groupsView.Groups.Count > 0;
Debug.Log("GroupsService.Subscribe 1: " + _groupsView.Groups.Count);
_data.GroupNames.Clear();
_data.GroupPlayerNames.Clear();
foreach(var groupView in groupsView.Groups)
{
string groupName = $"Name = {groupView.Group.name}, Players = {groupView.Group.members.Count}";
_data.GroupNames.Add(groupName);
foreach (var member in groupView.Group.members)
{
string groupPlayerName = $"Name = {member.gamerTag}";
_data.GroupPlayerNames.Add(groupPlayerName);
}
// Create a new chat room for the group
string roomName = $"Room For {groupView.Group.name}";
await _chatService.CreateRoom(roomName, false,
new List {{_beamContext.PlayerId}});
}
Refresh();
});
// Observe ChatService Changes
_chatService.Subscribe(chatView =>
{
_chatView = chatView;
int roomsWithPlayers = 0;
_data.RoomNames.Clear();
_data.RoomPlayerNames.Clear();
foreach(RoomHandle room in chatView.roomHandles)
{
// Optional: Only setup non-empty rooms
if (room.Players.Count > 0)
{
roomsWithPlayers++;
```
--------------------------------
### Initialize Telemetry in Main Entry Point
Source: https://docs.beamable.com/docs/cli-guide-microservice-logging
Invoke the telemetry and collector setup methods before starting the Beamable service.
```csharp
///
/// The entry point for the service.
///
public static async Task Main()
{
SetupTelemetry();
SetupCollector();
await BeamServer
.Create()
.IncludeRoutes(routePrefix: "")
.RunForever();
}
```
--------------------------------
### Initialize Steam Authentication in MonoBehaviour
Source: https://docs.beamable.com/docs/steam-integration-guide
Example implementation for the Start method to initialize Steam and trigger the sign-in flow.
```csharp
async void Start()
{
_beamContext = BeamContext.Default;
await _beamContext.OnReady;
Debug.Log($"Beamable User ID: {_beamContext.PlayerId}");
if (!SteamManager.Initialized)
{
Debug.Log("SteamManager not initialized.");
// This may happen if the player is not logged into Steam on their machine.
return;
}
var steamUserID = SteamUser.GetSteamID().ToString();
Debug.Log($"SteamUserID:{steamUserID}");
var ticket = await GetSteamAuthTicket();
Debug.Log($"Current Steam Ticket: {ticket}");
await SignInWithSteam(steamUserID, ticket);
}
```
--------------------------------
### Open Project Solution
Source: https://docs.beamable.com/docs/cli-project-open
Use this command to open the solution file for all services in your project. No specific setup is required beyond having the Beam CLI installed.
```shell
beam project open [options]
```
--------------------------------
### Start Services Docker Daemon
Source: https://docs.beamable.com/docs/cli-services-docker-start
Use this command to start the Docker daemon for Beamable services. Ensure Docker is installed and configured.
```shell
beam services docker start [options]
```
--------------------------------
### Example Usage of UserDataMicroService
Source: https://docs.beamable.com/docs/microstorages
Demonstrates how to use the UserDataServiceClient to interact with the UserDataService. Ensure Docker setup and server are running before executing.
```csharp
using System.Collections.Generic;
using UnityEngine;
using Beamable.Server.Clients;
namespace Beamable.Examples.Features.Microservices.UserDataMicroServiceExample
{
///
/// Demonstrates messages = await _userDataServiceClient.GetMessage(0, 0);
// #4 - Result = true
Debug.Log ($"GetMessage() messages.Count = {messages.Count}, messages[0] = {messages[0]}");
}
}
}
```
--------------------------------
### Start Matchmaking Process
Source: https://docs.beamable.com/docs/matchmaking-code
Initiates the matchmaking process. Ensure you have set up listeners for progress and completion events before calling this method. This example uses an experimental API.
```C#
private async void SetupBeamable()
{
// Partial code
var myMatchmaking = new MyMatchmaking (
_beamContext.Api.Experimental.MatchmakingService,
simGameType,
_beamContext.PlayerId);
myMatchmaking.OnProgress.AddListener(MyMatchmaking_OnProgress);
myMatchmaking.OnComplete.AddListener(MyMatchmaking_OnComplete);
myMatchmaking.OnError.AddListener(MyMatchmaking_OnError);
await myMatchmaking.StartMatchmaking();
}
```
--------------------------------
### Run Microservice
Source: https://docs.beamable.com/docs/cli-guide-microservice-logging
Start the service after configuring the environment variables.
```sh
dotnet run
```
--------------------------------
### Initialize and Start Google Sign-In
Source: https://docs.beamable.com/docs/google-play-game-services-sign-in-code
Initializes the SignInWithGPG wrapper and starts the Google login process. Subscribe to OnLoginResult and OnRequestServerSideAccessResult callbacks for handling login outcomes.
```csharp
SignInWithGPG _gpg;
///
/// Starts Google Login process, then calls `HandleLoginResult` and/or `HandleRequestServerSideAccessResult` with a results.
///
public void StartLogin()
{
_gpg = new SignInWithGPG();
_gpg.OnLoginResult += HandleLoginResult;
_gpg.OnRequestServerSideAccessResult += HandleRequestServerSideAccessResult;
_gpg.Login();
}
```
--------------------------------
### Example Common Library csproj File
Source: https://docs.beamable.com/docs/cli-guide-upgrading
A complete example of a csproj file for a common library created with CLI 2.0.1.
```xml
netstandard2.1
true
```
--------------------------------
### Start Local Server CLI
Source: https://docs.beamable.com/docs/cli-server-serve
Use this command to start a local server for the CLI. The owner argument is optional and identifies the server for the /info endpoint.
```shell
beam server serve [] [options]
```
--------------------------------
### Example Usage of Custom Connectivity Service
Source: https://docs.beamable.com/docs/connectivity-code
A MonoBehaviour example demonstrating how to utilize the custom connectivity service within a scene.
```csharp
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Beamable;
using Beamable.Api.Connectivity; // add this to docs
using UnityEngine;
using UnityEngine.Events;
///
/// Holds data for use in the .
///
[Serializable]
public class ConnectivityServiceData
{
public List OutputLogs = new List();
public bool HasConnectivity = false;
}
[Serializable]
public class RefreshedUnityEvent : UnityEvent { }
///
/// Demonstrates .
///
public class CustomConnectivityServiceExample : MonoBehaviour
{
// Events ---------------------------------------
[HideInInspector]
public RefreshedUnityEvent OnRefreshed = new();
// Fields ---------------------------------------
private BeamContext _beamContext;
private ConnectivityServiceData _data = new();
private IConnectivityService _connectivityService;
// Properties -----------------------------------
public ConnectivityServiceData Data => _data;
// Unity Methods --------------------------------
protected async void Start()
{
Debug.Log($"Start() Instructions...\n\n" +
" * Ensure Computer's Internet Is Active\n" +
" * Run The Scene\n" +
" * See Onscreen UI Show HasConnectivity = true\n" +
" * Ensure Computer's Internet Is NOT Active (e.g. Turn off wifi/ethernet)\n" +
" * See Onscreen UI Show HasConnectivity = false\n");
```
--------------------------------
### Matchmaking Service Example in C#
Source: https://docs.beamable.com/docs/matchmaking-code
This script demonstrates creating and joining multiplayer game matches using Beamable Multiplayer. It requires setup within the Unity editor and provides UI elements for interaction. Ensure you have the Beamable SDK integrated into your Unity project.
```csharp
using System.Collections.Generic;
using Beamable.Common.Content;
using UnityEngine;
using UnityEngine.Events;
namespace Beamable.Examples.Services.MatchmakingService
{
public enum SessionState
{
None,
Connecting,
Connected,
Disconnecting,
Disconnected
}
///
/// Holds data for use in the .
///
[System.Serializable]
public class MatchmakingServiceExampleData
{
public SessionState SessionState = SessionState.None;
public bool CanStart { get { return SessionState == SessionState.Disconnected;}}
public bool CanCancel { get { return SessionState == SessionState.Connected;}}
public List MainLogs = new List();
public List MatchmakingLogs = new List();
public List InstructionsLogs = new List();
}
[System.Serializable]
public class RefreshedUnityEvent : UnityEvent { }
///
/// Demonstrates the creation of and joining to a
/// Multiplayer game match with Beamable Multiplayer.
///
public class MatchmakingServiceExample : MonoBehaviour
{
// Events ---------------------------------------
[HideInInspector]
public RefreshedUnityEvent OnRefreshed = new RefreshedUnityEvent();
// Fields ---------------------------------------
///
/// This defines the matchmaking criteria including "NumberOfPlayers"
///
[SerializeField] private SimGameTypeRef _simGameTypeRef;
private BeamContext _beamContext;
private MyMatchmaking _myMatchmaking = null;
private SimGameType _simGameType = null;
private MatchmakingServiceExampleData _data = new MatchmakingServiceExampleData();
// Unity Methods --------------------------------
protected void Start()
{
string startLog = $"Start() Instructions..\n" +
$"\n * Play Scene" +
$"\n * View UI" +
$"\n * Press 'Start Matchmaking' Button \n\n";
Debug.Log(startLog);
_data.InstructionsLogs.Add("View UI");
_data.InstructionsLogs.Add("Press 'Start Matchmaking' Button");
SetupBeamable();
}
// Methods --------------------------------------
private async void SetupBeamable()
{
_beamContext = BeamContext.Default;
await _beamContext.OnReady;
Debug.Log($"beamContext.PlayerId = {_beamContext.PlayerId}\n\n");
_data.SessionState = SessionState.Disconnected;
_simGameType = await _simGameTypeRef.Resolve();
_data.MainLogs.Add($"beamContext.PlayerId = {_beamContext.PlayerId}");
_data.MainLogs.Add($"SimGameType.Teams.Count = {_simGameType.teams.Count}");
_myMatchmaking = new MyMatchmaking(
_beamContext.Api.Experimental.MatchmakingService,
_simGameType,
_beamContext.PlayerId);
_myMatchmaking.OnProgress.AddListener(MyMatchmaking_OnProgress);
_myMatchmaking.OnComplete.AddListener(MyMatchmaking_OnComplete);
_myMatchmaking.OnError.AddListener(MyMatchmaking_OnError);
Refresh();
}
public async void StartMatchmaking()
{
string log = $"StartMatchmaking()";
//Debug.Log(log);
_data.SessionState = SessionState.Connecting;
_data.MatchmakingLogs.Add(log);
Refresh();
await _myMatchmaking.StartMatchmaking();
}
public async void CancelMatchmaking()
{
string log = $"CancelMatchmaking()";
//Debug.Log(log);
_data.SessionState = SessionState.Disconnecting;
_data.MatchmakingLogs.Add(log);
Refresh();
await _myMatchmaking.CancelMatchmaking();
_data.SessionState = SessionState.Disconnected;
Refresh();
}
public void Refresh()
{
string refreshLog = $"Refresh() ...\n" +
$"\n * MainLogs.Count = {_data.MainLogs.Count}" +
```
--------------------------------
### Timed Rewards Microservice Example
Source: https://docs.beamable.com/docs/microservices-distributing
Demonstrates how to consume an imported Timed Rewards feature within a custom microservice. Ensure Docker and server setup are completed before running.
```csharp
using UnityEngine;
using Beamable.Server.Clients;
namespace Beamable.Examples.Features.Microservices.TimedRewardsMicroserviceExample
{
///
/// Demonstrates .
///
public class TimedRewardsMicroserviceExample : MonoBehaviour
{
// Properties -----------------------------------
// Fields ---------------------------------------
[SerializeField]
private TimeRewardRef _timeRewardRef = null;
private TimedRewardServiceClient _timedRewardServiceClient;
// Unity Methods --------------------------------
protected void Start()
{
Debug.Log("Start() Instructions...\n" +
"* Complete docker setup per https://docs.beamable.com/docs/microservices-feature\n" +
"* Start the server per https://docs.beamable.com/docs/microservices-feature\n" +
"* Play This Scene\n" +
"* Enjoy!\n\n\n");
SetupBeamable();
}
// Methods --------------------------------------
private async void SetupBeamable()
{
var beamableAPI = await Beamable.API.Instance;
Debug.Log($"beamableAPI.User.id = {beamableAPI.User.id}");
_timedRewardServiceClient = new TimedRewardServiceClient();
// #1 - Call Microservice
bool isSuccess = await _timedRewardServiceClient.Claim(_timeRewardRef);
// #2 - Result = true
Debug.Log ($"AddMyValues() isSuccess = {isSuccess}");
}
}
}
```
--------------------------------
### Example Beamable Service csproj File
Source: https://docs.beamable.com/docs/cli-guide-upgrading
A complete example of a csproj file for a Beamable microservice generated with CLI 2.0.1.
```xml
service
true
net6.0
```
--------------------------------
### Build Local Projects with Temp Solution
Source: https://docs.beamable.com/docs/cli-project-build-sln
Use this command to build all local projects using a temporary solution file. No specific setup is required beyond having the Beamable CLI installed.
```shell
beam project build-sln [options]
```
--------------------------------
### Initialize and Start Matchmaking
Source: https://docs.beamable.com/docs/matchmaking-code
Initializes the matchmaking service and starts a matchmaking request. Handles the case where matchmaking is already in progress.
```csharp
public async Task StartMatchmaking()
{
if (_myMatchmakingResult.IsInProgress)
{
Debug.LogError($"MyMatchmaking.StartMatchmaking() failed. " +
$"IsInProgress must not be {_myMatchmakingResult.IsInProgress}.\n\n");
return;
}
_myMatchmakingResult.IsInProgress = true;
_myMatchmakingResult.MatchmakingHandle = await _matchmakingService.StartMatchmaking(
_myMatchmakingResult.SimGameType.Id,
maxWait: TimeSpan.FromSeconds(10),
updateHandler: handle =
{
OnUpdateHandler(handle);
},
readyHandler: handle =
{
// Call both
OnUpdateHandler(handle);
OnReadyHandler(handle);
},
timeoutHandler: handle =
{
// Call both
OnUpdateHandler(handle);
OnTimeoutHandler(handle);
});
}
```
--------------------------------
### Install Beamable CLI
Source: https://docs.beamable.com/docs/cli-guide-getting-started
Installs the Beamable CLI globally as a .NET tool. Ensure Dotnet 8 is installed first.
```shell
dotnet tool install --global Beamable.Tools
```
--------------------------------
### Federation Data Example
Source: https://docs.beamable.com/docs/cli-guide-microservice-federation
An example output from 'dotnet beam fed list' showing service details and configured federations.
```json
{
"cid": "1338004997867618",
"pid": "DE_1754280032981028",
"services": [
{
"beamoName": "ExampleService",
"routingKey": "chriss-macbook-pro-2_59e8e38ad189aefe093dfa7d74e18841",
"federations": {
"myId": [
{
"interface": "IFederatedLogin"
}
]
}
}
```
--------------------------------
### Initialize Unreal Project
Source: https://docs.beamable.com/docs/cli-unreal-init
Executes the automated setup for an Unreal project using the specified SDK path and project file.
```shell
beam unreal init [options]
```
--------------------------------
### Example Output of Deploy Plan
Source: https://docs.beamable.com/docs/cli-guide-microservice-deployment
Sample output showing the result of running the deploy plan command.
```text
$ dotnet beam deploy plan
fetching latest ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100%
build DiscordSampleMs ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100%
build HathoraDemo ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100%
build LiveOpsDemoMS ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100%
build MSPlayground ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100%
build SteamDemo ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100%
calculating plan ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100%
Adding 5 services
- DiscordSampleMs
- HathoraDemo
- LiveOpsDemoMS
- MSPlayground
- SteamDemo
Enabling 3 federations
- DiscordSampleMs [IFederatedLogin/discord]
- HathoraDemo [IFederatedGameServer/hathora]
- SteamDemo [IFederatedLogin/steam]
Adding 1 storage
- DBPlayground
Uploading 5 services
- HathoraDemo
- MSPlayground
- LiveOpsDemoMS
- SteamDemo
- DiscordSampleMs
Local Health-checks were not run! Services may work as expected, but they have not been explicitly tested locally.
Consider re-running a plan command with the `--health` option.
This plan has 14 pending changes!
To release, use `dotnet beam deploy release --plan E:\UnrealProjects\BeamableUnreal\.beamable\temp\plans\plan-1733140465006.plan.json`
Saved plan: E:\UnrealProjects\BeamableUnreal\.beamable\temp\plans\plan-1733140465006.plan.json
```
--------------------------------
### Setup Beamable Context and Subscribe to Services
Source: https://docs.beamable.com/docs/stores-custom-stores
Initializes the Beamable context, resolves store content, and subscribes to Inventory, Currency, and Commerce services. Ensure your internet connection is active.
```csharp
private async void SetupBeamable()
{
_beamContext = BeamContext.Default;
await _beamContext.OnReady;
Debug.Log($"beamContext.PlayerId = {_beamContext.PlayerId}");
_storeContent = await _storeRef.Resolve();
// Observe Changes
_beamContext.Api.InventoryService.Subscribe(ItemContentType, Inventory_OnChanged);
_beamContext.Api.InventoryService.Subscribe(CurrencyContentType, Currency_OnChanged);
_beamContext.Api.CommerceService.Subscribe(_storeContent.Id, CommerceService_OnChanged);
// Update UI Immediately
Refresh();
}
```
--------------------------------
### Stop a Running Service
Source: https://docs.beamable.com/docs/cli-project-stop
Use this command to stop a running service. No specific setup is required beyond having the beam CLI installed.
```shell
beam project stop [options]
```
--------------------------------
### Prune Telemetry Data
Source: https://docs.beamable.com/docs/cli-telemetry-prune
Use this command to clear telemetry data that has been exported to files. No specific setup is required beyond having the CLI installed.
```shell
beam telemetry prune [options]
```
--------------------------------
### Implement StartTheBattle Method
Source: https://docs.beamable.com/docs/microservices-bbb-guide
This updated microservice method handles the start of a battle. It resolves Boss data, sets the Boss's health, and prepares for combat. Ensure `BossContentRef` and `heroWeaponIndexMax` are correctly provided.
```csharp
namespace Beamable.Server.BBBGameMicroservice
{
[Microservice("BBBGameMicroservice")]
public class BBBGameMicroservice : Microservice
{
[ClientCallable]
public async Task StartTheBattle(BossContentRef bossContentRef, int heroWeaponIndexMax)
{
// Find the Boss data from the Boss content
var boss = await bossContentRef.Resolve();
// Set boss health to 100
await BBBHelper.SetProtectedPlayerStat(Services, Context.UserId,
BBBConstants.StatKeyBossHealth,
```
--------------------------------
### Cloud Saving Service Implementation
Source: https://docs.beamable.com/docs/player-cloud-save-code
Demonstrates initialization, manual file synchronization, and data management using the Beamable Cloud Saving Service. This example is for reference purposes only.
```csharp
using Beamable;
using Beamable.Api.CloudSaving;
using Beamable.Common;
using Beamable.Player.CloudSaving;
using System;
using System.Globalization;
using System.Text;
using UnityEngine;
using Random = UnityEngine.Random;
public class CloudSaving_Sample : MonoBehaviour
{
private const string MAIN_SAVE_TXT = "main_save.txt";
private const string BACKUP_SAVE_TXT = "backup_save.txt";
private const string BYTE_SAVE_DAT = "byte_save.dat";
private const string GAME_SAVE_JSON = "game_save.json";
private ICloudSavingService _cloudSavingService;
private bool _init;
private void Awake()
{
InitServiceAsync();
}
[ContextMenu("Check Save Data")]
public void CheckSaveData()
{
CheckSaveDataAsync();
}
[ContextMenu("Update Save File")]
public void SaveFile()
{
_ = SaveFileAsync();
}
[ContextMenu("Force Upload Save File")]
public void ForceUploadSaveFile()
{
ForceUploadSaveFileAsync();
}
[ContextMenu("Force Download Save File")]
public void ForceDownloadSaveFile()
{
ForceDownloadSaveFileAsync();
}
[ContextMenu("Update Save Files")]
public void UpdateSaveFiles()
{
// Use Update Function to Handle Manifest Changes that require to commit them to Cloud
_cloudSavingService.Update(builder =>
{
builder.ArchiveSaveData(BACKUP_SAVE_TXT);
builder.RenameSaveData(GAME_SAVE_JSON, "Player_Save.json");
builder.ForgetSaveData(BYTE_SAVE_DAT);
});
}
private async void InitServiceAsync()
{
// Get BeamContext
BeamContext context = await BeamContext.Default.Instance;
_cloudSavingService = context.CloudSaving;
// Register to CloudSavingError and OnManifestUpdate | This is optional, use it if you need to handle it by yourself
_cloudSavingService.OnCloudSavingError += OnCloudSavingError;
_cloudSavingService.OnManifestUpdated += OnManifestUpdated;
// Init System and start to check for Local and Remote Changes
await _cloudSavingService.Init(3);
Debug.Log("Cloud Saving Service Initialized");
}
private void OnManifestUpdated(CloudSavingManifest manifest)
{
Debug.Log($"Manifest Updated. Items Count: {manifest.manifest.Count}");
}
private void OnCloudSavingError(CloudSavingError error)
{
Debug.Log($"Cloud Saving Error: {error.Message}");
}
private async void CheckSaveDataAsync()
{
// Load Data from Save and Check their contents
string mainSaveContent = await _cloudSavingService.LoadDataString(MAIN_SAVE_TXT);
Debug.Log($"Main Save Data: {mainSaveContent}");
string backupSaveContent = await _cloudSavingService.LoadDataString(BACKUP_SAVE_TXT);
Debug.Log($"Backup Save Data: {backupSaveContent}");
byte[] byteDataContent = await _cloudSavingService.LoadDataByte(BYTE_SAVE_DAT);
Debug.Log($"Byte Save Data: {byteDataContent}");
var gameSaveContent = await _cloudSavingService.LoadData(GAME_SAVE_JSON);
Debug.Log(
$"Game Save Data: Level: {gameSaveContent.level} | Score: {gameSaveContent.score} | ExtraData: {gameSaveContent.extraData}");
}
private async Promise SaveFileAsync(string forceContent = null)
{
// Save files with random with Forced value or with random values
string contents = string.IsNullOrEmpty(forceContent)
? DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)
: forceContent;
await _cloudSavingService.SaveData(MAIN_SAVE_TXT, contents);
await _cloudSavingService.SaveData(BACKUP_SAVE_TXT, contents);
GameSave gameSave = new GameSave()
{
level = Random.Range(1, 11), score = Random.Range(1, 100), extraData = Guid.NewGuid().ToString(),
};
await _cloudSavingService.SaveData(GAME_SAVE_JSON, gameSave);
byte[] encodedBytes = Encoding.Default.GetBytes(contents);
await _cloudSavingService.SaveData(BYTE_SAVE_DAT, encodedBytes);
}
private async void ForceUploadSaveFileAsync()
{
// Force change Files Values and Force them to be uploaded to Cloud
await SaveFileAsync($"ForcedContent-{DateTime.Now.ToString(CultureInfo.InvariantCulture)}");
await _cloudSavingService.ForceUploadLocalData();
}
private async void ForceDownloadSaveFileAsync()
{
// Force download Cloud Values replacing any Local Changes.
await _cloudSavingService.ForceDownloadCloudData();
}
[Serializable]
private class GameSave
{
public int level;
public float score;
public string extraData;
}
}
```
--------------------------------
### Remove Realm Config
Source: https://docs.beamable.com/docs/cli-config-realm-remove
Use this command to remove realm configuration values. No specific setup is required beyond having the beam CLI installed.
```shell
beam config realm remove [options]
```
--------------------------------
### Get federation local settings via CLI
Source: https://docs.beamable.com/docs/cli-federation-local-settings-get
Executes the command to retrieve local settings for a federation. Requires the Beamable CLI to be installed and configured.
```shell
beam federation local-settings get [options]
```
--------------------------------
### Create a new microservice project
Source: https://docs.beamable.com/docs/cli-project-new-service
Use this command to initialize the directory structure and configuration for a new microservice.
```shell
beam project new service [options]
```
--------------------------------
### Access Telemetry Commands
Source: https://docs.beamable.com/docs/cli-telemetry
Use this command to access Open Telemetry related functionalities. No specific setup is required beyond having the Beamable CLI installed.
```shell
beam telemetry [options]
```
--------------------------------
### Implement Multiplayer Session with SimClient
Source: https://docs.beamable.com/docs/multiplayer-code
This example demonstrates how to initialize a Beamable context, manage session states, and use the SimClient to handle network events in a Unity environment.
```csharp
using System.Collections.Generic;
using Beamable.Experimental.Api.Sim;
using UnityEngine;
using UnityEngine.Events;
namespace Beamable.Examples.Services.Multiplayer
{
[System.Serializable]
public class MultiplayerExampleDataEvent : UnityEvent { }
public enum SessionState
{
None,
Initializing,
Initialized,
Connected,
Disconnected
}
///
/// Holds data for use in the .
///
[System.Serializable]
public class MultiplayerExampleData
{
public string MatchId = null;
public string SessionSeed;
public long CurrentFrame;
public long LocalPlayerDbid;
public bool IsSessionConnected { get { return SessionState == SessionState.Connected; }}
public SessionState SessionState = SessionState.None;
public List PlayerMoveLogs = new List();
public List PlayerDbids = new List();
}
///
/// Defines a simple type of in-game "move" sent by a player
///
public class MyPlayerMoveEvent
{
public static string Name = "MyPlayerMoveEvent";
public long PlayerDbid;
public Vector3 Position;
public MyPlayerMoveEvent(long playerDbid, Vector3 position)
{
PlayerDbid = playerDbid;
Position = position;
}
public override string ToString()
{
return $"[MyPlayerMoveEvent({Position})]";
}
}
///
/// Demonstrates .
///
public class MultiplayerExample : MonoBehaviour
{
// Events ---------------------------------------
[HideInInspector]
public MultiplayerExampleDataEvent OnRefreshed = new MultiplayerExampleDataEvent();
// Fields ---------------------------------------
private MultiplayerExampleData _multiplayerExampleData = new MultiplayerExampleData();
private const long FramesPerSecond = 20;
private const long TargetNetworkLead = 4;
private SimClient _simClient;
private BeamContext _beamContext;
// Unity Methods --------------------------------
protected void Start()
{
Debug.Log($"Start() Instructions...\n\n" +
" * Run The Scene\n" +
" * Press 'Start Multiplayer'\n" +
" * Press 'Send Player Move'\n" +
" * See results in the in-game UI\n");
SetupBeamable();
}
protected void Update()
{
if (_simClient != null)
{
_simClient.Update();
}
string refreshString = "";
refreshString += $"MatchId: {_multiplayerExampleData.MatchId}\n";
refreshString += $"Seed: {_multiplayerExampleData.SessionSeed}\n";
refreshString += $"Frame: {_multiplayerExampleData.CurrentFrame}\n";
refreshString += $"Dbids:";
foreach (var dbid in _multiplayerExampleData.PlayerDbids)
{
refreshString += $"{dbid},";
}
//Debug.Log($"message:{refreshString}");
}
protected void OnDestroy()
{
if (_simClient != null)
{
StopMultiplayer();
}
}
// Methods --------------------------------------
private async void SetupBeamable()
{
_beamContext = BeamContext.Default;
await _beamContext.OnReady;
Debug.Log($"_beamContext.PlayerId = {_beamContext.PlayerId}");
// Access Local Player Information
_multiplayerExampleData.LocalPlayerDbid = _beamContext.PlayerId;
}
public void StartMultiplayer()
{
if (_simClient != null)
{
StopMultiplayer();
}
_multiplayerExampleData.SessionState = SessionState.Initializing;
Refresh();
// Generates a specific MatchId
// (Otherwise use Beamable's MatchmakingService)
_multiplayerExampleData.MatchId = "MyCustomMatchId_" + UnityEngine.Random.Range(0,99999);
// Create Multiplayer Session
_simClient = new SimClient(
new SimNetworkEventStream(_multiplayerExampleData.MatchId, _beamContext.ServiceProvider),
FramesPerSecond, TargetNetworkLead);
```
--------------------------------
### Get Access Token From Refresh Token
Source: https://docs.beamable.com/docs/cli-token-from-refresh
Use this command to exchange a refresh token for a new access token. Ensure you have the Beamable CLI installed and configured.
```shell
beam token from-refresh [options]
```
--------------------------------
### Explore Beamable Tokens CLI
Source: https://docs.beamable.com/docs/cli-token
Use this command to explore available options for managing Beamable tokens. No setup is required beyond having the Beamable CLI installed.
```shell
beam token [options]
```
--------------------------------
### Service Initialization Log
Source: https://docs.beamable.com/docs/cli-guide-microservices
Example log output indicating a successfully initialized and ready standalone microservice.
```log
13:25:33.077 [DBUG] Service provider initialized
13:25:33.307 [DBUG] Event provider initialized
13:25:33.308 [INFO] Service ready for traffic.baseVersion=2.0.0-PREVIEW.RC2 executionVersion= portalURL=https://portal.beamable.com/cid/games/DE_1751365810229268/realms/pid/microservices/HelloWorld/docs?refresh_token=redacted&prefix=redacted
```
--------------------------------
### Check Grafana Status
Source: https://docs.beamable.com/docs/cli-grafana-ps
Use this command to determine if a local Grafana server is currently active for your project. No specific setup is required beyond having the Beamable CLI installed.
```shell
beam grafana ps [options]
```
--------------------------------
### List Beamable Service Routes
Source: https://docs.beamable.com/docs/cli-config-routes
Use this command to list the available service routes for your Beamable host. No specific setup is required beyond having the Beamable CLI installed.
```shell
beam config routes [options]
```
--------------------------------
### Create New Projects
Source: https://docs.beamable.com/docs/cli-guide-microservice-cli-workflows
Initialize new microservices, storage, or common libraries within a .beamable workspace.
```sh
dotnet beam project new service # create a new Microservice
dotnet beam project new storage # create a new Storage
dotnet beam project new common-lib # create a new Common Library
```
--------------------------------
### List Available CLI Servers
Source: https://docs.beamable.com/docs/cli-server-ps
Use this command to view a list of all available servers within the CLI environment. No specific setup is required beyond having the Beamable CLI installed.
```shell
beam server ps [options]
```
--------------------------------
### List Running Status of Local Services
Source: https://docs.beamable.com/docs/cli-content-ps
Use this command to check the status of local services that are not managed by Docker. No specific setup is required beyond having the Beamable CLI installed.
```shell
beam content ps [options]
```
--------------------------------
### Start Listening to Server Events
Source: https://docs.beamable.com/docs/cli-listen-server
Use this command to initiate monitoring of realm events. Requires admin privileges and a configured CLI. This tool is for diagnostics and lacks robust connection recovery.
```shell
beam listen server [options]
```
--------------------------------
### Implement In-App Purchase Logic in C#
Source: https://docs.beamable.com/docs/stores-android-iap
This script demonstrates how to initialize Beamable, resolve a listing, validate a SKU, and initiate a purchase. It handles both editor testing and device deployment, deferring to platform services on devices.
```csharp
using Beamable;
using Beamable.Common.Shop;
using UnityEngine;
public class IAPExample : MonoBehaviour
{
private BeamContext _context;
private async void Start()
{
_context = BeamContext.Default;
await _context.OnReady;
Debug.Log($
```
--------------------------------
### Set and Get Stats using StatBehaviour
Source: https://docs.beamable.com/docs/stats-guide
Use StatBehaviour for a simplified approach to managing stats. Attach it to a GameObject and configure it in the Inspector. This example demonstrates setting a value and logging it when received.
```csharp
using Beamable.Stats;
using UnityEngine;
namespace Beamable.Examples.Services.StatsService
{
///
/// Demonstrates .
///
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}");
}
}
}
```
--------------------------------
### Initialize Beamable Project
Source: https://docs.beamable.com/docs/cli-guide-getting-started
Initializes a new Beamable project by connecting to an organization. This command prompts for organization alias, credentials, and realm, creating a .beamable folder.
```shell
mkdir MyProject
beam init
```
--------------------------------
### Reset Local Content to Match Remote
Source: https://docs.beamable.com/docs/cli-content-reset
Use this command to set your local content to match the remote content. No specific setup or imports are required beyond having the Beamable CLI installed.
```shell
beam content reset [options]
```
--------------------------------
### Initialize a Beamable Project
Source: https://docs.beamable.com/docs/cli-guide-microservice-debugging
Commands to create a new project workspace and generate a new microservice.
```sh
beam init MyProject
cd MyProject
dotnet beam project new service HelloWorld
```
--------------------------------
### Getting Unescaped JSON Values with JQ
Source: https://docs.beamable.com/docs/cli-guide-command-line-outout
When you need the unescaped JSON value (e.g., a string without quotes), use the `fromjson` component of JQ. This example extracts the `cid` value as a number.
```sh
beam config | jq '.data.cid | fromjson'
```
--------------------------------
### Open Content Folder with Beamable CLI
Source: https://docs.beamable.com/docs/cli-content
Use this command to open the project's content folder in your system's file explorer. No specific setup is required beyond having the Beamable CLI installed.
```shell
beam content [options]
```
--------------------------------
### CLI: beam unreal select-sample
Source: https://docs.beamable.com/docs/cli-unreal-select-sample
Configures the current UnrealSDK repository root to act as a specific sample project.
```APIDOC
## CLI COMMAND: beam unreal select-sample
### Description
Run this command while inside the root of the UnrealSDK repository to configure the environment as a particular sample project.
### Usage
`beam unreal select-sample [options]`
### Arguments
- **sample-name** (String) - Required - The name of the sample project. Can be provided with or without the "BEAMPROJ_" prefix.
```
--------------------------------
### GET /basic/tournaments/global
Source: https://docs.beamable.com/reference/get_basic-tournaments-global
Retrieves global tournament standings. This endpoint allows fetching standings for a specific tournament, with options to limit the number of results, focus on a particular player's rank, and specify a cycle or starting point for the data.
```APIDOC
## GET /basic/tournaments/global
### Description
Retrieves global tournament standings. This endpoint allows fetching standings for a specific tournament, with options to limit the number of results, focus on a particular player's rank, and specify a cycle or starting point for the data.
### Method
GET
### Endpoint
/basic/tournaments/global
### Parameters
#### Query Parameters
- **tournamentId** (string) - Optional - The ID of the tournament to retrieve standings for.
- **max** (integer) - Optional - The maximum number of entries to return.
- **focus** (integer) - Optional - The player ID to focus the standings around.
- **cycle** (integer) - Optional - The tournament cycle to retrieve standings for.
- **from** (integer) - Optional - The starting index for pagination.
### Request Example
```json
{
"example": "request body"
}
```
### Response
#### Success Response (200)
- **entries** (array) - A list of tournament entries, each containing player rank, score, rewards, player ID, and stage change.
- **me** (object) - The current player's tournament entry details.
#### Response Example
```json
{
"entries": [
{
"rank": 1,
"score": 1000.5,
"currencyRewards": [
{
"symbol": "gold",
"amount": 100
}
],
"playerId": 12345,
"stageChange": 0
}
],
"me": {
"rank": 5,
"score": 800.0,
"currencyRewards": [
{
"symbol": "silver",
"amount": 50
}
],
"playerId": 67890,
"stageChange": -1
}
}
```
```
--------------------------------
### Initialize SignInWithApple Instance
Source: https://docs.beamable.com/docs/apple-sign-in-code
Instantiate the SignInWithApple class. This should be done once when your component starts.
```csharp
private SignInWithApple signInWithApple;
private void Start()
{
signInWithApple = new SignInWithApple();
}
```
--------------------------------
### Set and Get Stats using Raw C# Coding
Source: https://docs.beamable.com/docs/stats-guide
Utilize raw C# coding for maximum flexibility in managing stats. This example shows how to set a stat value and then retrieve it using the StatsService API after ensuring the Beamable context is ready.
```csharp
using System.Collections.Generic;
using UnityEngine;
namespace Beamable.Examples.Services.StatsService
{
///
/// Demonstrates .
///
public class StatCodingExample : MonoBehaviour
{
// Unity Methods --------------------------------
protected void Start()
{
Debug.Log($"Start()")
SetupBeamable();
}
// Other Methods ------------------------------
private async void SetupBeamable()
{
var context = BeamContext.Default;
await context.OnReady;
Debug.Log($"context.PlayerId = {context.PlayerId}");
string statKey = "MyExampleStat";
string access = "public";
string domain = "client";
string type = "player";
long id = context.PlayerId;
// Set Value
Dictionary setStats =
new Dictionary() { { statKey, "99" } };
await context.Api.StatsService.SetStats(access, setStats);
// Get Value
Dictionary getStats =
await context.Api.StatsService.GetStats(domain, access, type, id);
string myExampleStatValue = "";
getStats.TryGetValue(statKey, out myExampleStatValue);
Debug.Log($"myExampleStatValue = {myExampleStatValue}");
}
}
}
```
--------------------------------
### Complete Announcements Script
Source: https://docs.beamable.com/docs/announcements-code
A full example script integrating initialization, retrieval, subscription, and display logic.
```csharp
using System.Collections.Generic;
using System.Threading.Tasks;
using Beamable;
using Beamable.Common.Api.Announcements;
using UnityEngine;
public class AnnouncementsTest : MonoBehaviour
{
private BeamContext _beamContext;
private async void Start()
{
_beamContext = BeamContext.Default;
await _beamContext.OnReady;
Debug.Log($"User Id: {_beamContext.PlayerId}");
var announcements = await GetAnnouncements();
PrintAnnouncements(announcements);
SubscribeToAnnouncements();
}
private async Task> GetAnnouncements()
{
var response = await _beamContext.Api.AnnouncementService.GetCurrent();
return response?.announcements;
}
private void SubscribeToAnnouncements()
{
_beamContext.Api.AnnouncementService.Subscribe(response =>
{
PrintAnnouncements(response?.announcements);
});
}
private void PrintAnnouncements(List announcements)
{
foreach (var announcement in announcements)
{
Debug.Log(announcement.title);
Debug.Log(announcement.body);
}
}
}
```