Documentation

Support

Use case sample: Initialize newly signed-up players with default configuration values

Initialize new players with default values in Cloud Save when they first sign up.
Read time 4 minutesLast updated 18 hours ago

The use case sample demonstrates how to use Triggers to initialize new players with a default health and stamina values in Cloud Save when they first sign up. It uses the
signedUp
event emitted by the Authentication service, and records the value in Cloud Save.

Prerequisites

You must first create a service account with required access roles and configure the UGS CLI.

Authenticate using a Service Account

Before you can call the Triggers service, you must authenticate using a Service Account.
  1. Navigate to the Unity Dashboard.
  2. Select Administration > Service Accounts.
  3. Select the New button and enter a name and description for the Service Account.
  4. Select Create.
Add Product roles and create a key:
  1. Select Manage product roles.
  2. Add the following roles to the Service Account:
    • From the LiveOps dropdown, select Triggers Configuration Editor and Triggers Configuration Viewer.
    • From the Admin dropdown, select Unity Environments Viewer.
  3. Select Save.
  4. Select Add Key.
  5. Encode the Key ID and Secret key using base64 encoding. The format is “key_id:secret_key”. Note this value down.
For more information, refer to Authentication.

Configure the UGS CLI

Follow the steps below to get stated with the UGS CLI:
  1. Install the UGS CLI.
  2. Configure your Project ID and Environment as such:
    ugs config set project-id <your-project-id>

    ugs config set environment-name <your-environment-name>
  3. Authenticate using the Service account you created earlier. Refer to Get Authenticated.

Examine the
signed-up
event

The Authentication service emits a
signed-up
event when a new player is created. The event payload looks like this:
{ "playerId": "string", "providerId": "string", "createdAt": "string"}
The event payload is passed on to Cloud Code as parameters. Refer to Authentication: Signed up for more information.

Set up Cloud Code

Define a module endpoint or a script that calls Cloud Save to initialize a newly authenticated player with default health and stamina values.

Cloud Code C# module

Create a
InitializeNewPlayer
module function with required string argument
playerId
with contents as below:
using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCode.Apis;using Unity.Services.CloudCode.Shared;using Unity.Services.CloudSave.Model;public class ModuleSample{ private const string HealthKey = "HEALTH"; private const string StaminaKey = "STAMINA"; private const int DefaultValue = 100; private readonly ILogger<ModuleSample> _logger; public ModuleSample(ILogger<ModuleSample> logger) { _logger = logger; } [CloudCodeFunction("InitializeNewPlayer")] public async Task InitializeNewPlayer(IExecutionContext ctx, IGameApiClient gameApiClient, string playerId) { try { var response = await gameApiClient.CloudSaveData.GetItemsAsync(ctx, ctx.ServiceToken, ctx.ProjectId, playerId, new List<string>() { HealthKey, StaminaKey }); if (response.Data.Results.Count == 0) { await gameApiClient.CloudSaveData.SetItemBatchAsync(ctx, ctx.ServiceToken, ctx.ProjectId, playerId, new SetItemBatchBody(new List<SetItemBody>{new (HealthKey, DefaultValue), new (StaminaKey, DefaultValue)})); _logger.LogInformation("The player has been initialized with the {HealthKey} and {StaminaKey} keys with values of {DefaultValue}", HealthKey, StaminaKey, DefaultValue); } } catch (ApiException e) { _logger.LogError("Failed to initialize player data in Cloud Save. Error: {Error}", e.Message); throw new Exception($"Failed to initialize {playerId} data in Cloud Save. Error: {e.Message}"); } } public class ModuleConfig : ICloudCodeSetup { public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton(GameApiClient.Create()); } }}
Deploy the module. Refer to Deploying Hello World to learn how to deploy a module.

Cloud Code JavaScript script

Create a
InitializeNewPlayer
script with a required string parameter
playerId
using the contents as below:

JavaScript

const { DataApi } = require("@unity-services/cloud-save-1.4");const CLOUD_SAVE_HEALTH_KEY = "HEALTH";const CLOUD_SAVE_STAMINA_KEY = "STAMINA";const DEFAULT_VALUE = 100;module.exports = async ({ params, context, logger }) => { const cloudSaveApi = new DataApi(context); try { // Check if player has been initialized yet const cloudSaveGetResponse = await cloudSaveApi.getItems(context.projectId, params.playerId, [CLOUD_SAVE_HEALTH_KEY, CLOUD_SAVE_STAMINA_KEY]); if (cloudSaveGetResponse.data.results.length === 0) { // Record new values for player await cloudSaveApi.setItemBatch(context.projectId, params.playerId, { data: [ { key: CLOUD_SAVE_HEALTH_KEY, value: DEFAULT_VALUE, }, { key: CLOUD_SAVE_STAMINA_KEY, value: DEFAULT_VALUE, }, ], }); logger.info(`The player has been initialized with the ${CLOUD_SAVE_HEALTH_KEY} and ${CLOUD_SAVE_STAMINA_KEY} keys with values of ${DEFAULT_VALUE}`, { affectedPlayerId: params.playerId }); return; } logger.info("The player has already been initialized.", { affectedPlayerId: params.playerId }); } catch (err) { logger.error("Failed to update Cloud Save data", { "error.message": err.message }, { affectedPlayerId: params.playerId }); throw err; }};// Uncomment the code below to enable the inline parameter definition// - Requires Cloud Code JS dev environment setup with NodeJS (https://docs.unity3d.com/Packages/com.unity.services.cloudcode@latest/index.html?subfolder=/manual/Authoring/javascript_project.html)//// module.exports.params = {// playerId: { type: "String", required: true },// };
Refer to Deploying Hello World to learn how to deploy a script.

Configure a trigger

To connect your Cloud Code resource to the Authentication
signed-up
event, create a trigger. The trigger executes the Cloud Code script or module when the event is fired, for example, every time a new player signs up.
Run the
new-file
command to create a trigger configuration locally:
ugs triggers new-file triggers-config
If you created a Cloud Code script, update the
triggers-config.tr
file with the following configuration:
{ "$schema": "https://ugs-config-schemas.unity3d.com/v1/triggers.schema.json", "Configs": [ { "Name": "initialize-new-player", "EventType": "com.unity.services.player-auth.signed-up.v1", "ActionUrn": "urn:ugs:cloud-code:InitializeNewPlayer", "ActionType": "cloud-code" } ]}
If you created a Cloud Code module, update the
triggers-config.tr
file with the following configuration:
{ "$schema": "https://ugs-config-schemas.unity3d.com/v1/triggers.schema.json", "Configs": [ { "Name": "initialize-new-player", "EventType": "com.unity.services.player-auth.signed-up.v1", "ActionUrn": "urn:ugs:cloud-code:ModuleSample/InitializeNewPlayer", "ActionType": "cloud-code" } ]}
Deploy the configuration using the UGS CLI tool:
ugs deploy triggers-config.tr
You should get a response similar to the following:
Deployed:triggers-config.tr
Now you have a trigger that executes your Cloud Code script or module when a player signs up.

Validate the result

To validate the result, sign up a new player using the Authentication service. This can be done by calling out to any Unity Gaming Service that's authenticated as a player. For example, to trigger the player authentication flow, you can select the Generate icon to generate a new player ID through the Cloud Code script page in the Unity Dashboard. Given the trigger is configured to fire on the
signed-up
event, every new player that signs up, their values are initialized in Cloud Save.
  1. Navigate to the Unity Dashboard.
  2. Select Products > Player Management.
  3. Select one of the players from the list.
  4. Navigate to the Cloud Save > Data tab.
  5. You should find the
    HEALTH
    and
    STAMINA
    keys with the default values of
    100
    .