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 3 months 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 event emitted by the Authentication service, and records the value in Cloud Save.
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.
- In the Unity Dashboard, open the Account menu and select Manage organization.
- In the Administration menu, select Service Accounts.
- Select the New button and enter a name and description for the Service Account.
- Select Create.
Add Product roles and create a key:
- 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.
For more information, refer to Authentication.
Configure the UGS CLI
Follow the steps below to get stated with 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
signed-upThe Authentication service emits a event when a new player is created. The event payload looks like this:
signed-up{ "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 module function with required string argument with contents as below:
InitializeNewPlayerplayerIdusing 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<IGameApiClient>(GameApiClient.Create()); } }}
Deploy the module.
Refer to Deploying Hello World to learn how to deploy a module.
Cloud Code JavaScript script
Create a script with a required string parameter using the contents as below:
InitializeNewPlayerplayerIdJavaScript
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 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.
signed-upRun the command to create a trigger configuration locally:
new-fileugs triggers new-file triggers-config
If you created a Cloud Code script, update the file with the following configuration:
triggers-config.tr{ "$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 file with the following configuration:
triggers-config.tr{ "$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 event, every new player that signs up, their values are initialized in Cloud Save.
signed-up- In the Unity Dashboard, go to Development > Products.
- Select 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