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
signedUpPrerequisites
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.- Navigate to the Unity Dashboard.
- Select Administration > Service Accounts.
- Select the New button and enter a name and description for the Service Account.
- Select Create.
- Select Manage product roles.
- 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.
- From the LiveOps dropdown, select Triggers Configuration Editor and Triggers Configuration Viewer.
- Select Save.
- Select Add Key.
- Encode the Key ID and Secret key using base64 encoding. The format is “key_id:secret_key”. Note this value down.
Configure the UGS CLI
Follow the steps below to get stated with the UGS CLI:- Install the UGS CLI.
-
Configure your Project ID and Environment as such:
ugs config set project-id <your-project-id>
ugs config set environment-name <your-environment-name> - Authenticate using the Service account you created earlier. Refer to Get Authenticated.
Examine the signed-up
event
The Authentication service emits a signed-upsigned-upThe event payload is passed on to Cloud Code as parameters. Refer to Authentication: Signed up for more information.{ "playerId": "string", "providerId": "string", "createdAt": "string"}
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 aInitializeNewPlayerplayerIdDeploy the module. Refer to Deploying Hello World to learn how to deploy a module.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()); } }}
Cloud Code JavaScript script
Create aInitializeNewPlayerplayerIdJavaScript
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 Authenticationsigned-upnew-fileIf you created a Cloud Code script, update theugs triggers new-file triggers-config
triggers-config.trIf you created a Cloud Code module, update the{ "$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" } ]}
triggers-config.trDeploy the configuration using the UGS CLI tool:{ "$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" } ]}
You should get a response similar to the following:ugs deploy triggers-config.tr
Now you have a trigger that executes your Cloud Code script or module when a player signs up.Deployed:triggers-config.tr
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 thesigned-up- Navigate to the Unity Dashboard.
- Select Products > Player Management.
- Select one of the players from the list.
- Navigate to the Cloud Save > Data tab.
- You should find the and
HEALTHkeys with the default values ofSTAMINA.100