Get started
Follow this workflow to set up Triggers and automate rewarding top players from Leaderboards.
Read time 6 minutesLast updated 18 hours ago
This section describes all the steps you need to get started with Triggers. The sample below demonstrates how to use Triggers to reward players the top five players from Leaderboards with an seasonal trophy in Cloud Save using a one-time schedule event emitted by the Scheduler.
Video Walkthrough
Watch the video below to see a walkthrough of the steps to create a trigger in the Unity Dashboard.Typical workflow
To get started with Triggers, follow these steps:- Create a Cloud Code script or module to be run on event: Define game logic to execute when the event is fired.
- Schedule an event to change the state of a resource: Define when the event is fired.
- Configure a trigger to execute the Cloud Code module endpoint on event: Define which Cloud Code script or module is executed when the event is fired.
- Validate the result: Check that the Cloud Code script or module has been executed.
Prerequisites
The steps assume you have already created a Unity Gaming Services project in the Unity Dashboard. 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 Scheduling and Triggers services, 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, Triggers Configuration Viewer, Scheduler Configuration Editor, Scheduler Configuration Viewer, and Leaderboards Admin.
- From the Admin dropdown, select Unity Environments Viewer.
- From the LiveOps dropdown, select Triggers Configuration Editor, Triggers Configuration Viewer, Scheduler Configuration Editor, Scheduler Configuration Viewer, and Leaderboards Admin.
- 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.
Set up Leaderboards
To follow this sample, you should create a leaderboard. You can use the UGS CLI to deploy the followingleaderboard.lbnew-fileThe file name corresponds to the leaderboard ID. Update theugs leaderboards new-file leaderboard
leaderboard.lbDeploy the file using the UGS CLI tool:{ "$schema": "https://ugs-config-schemas.unity3d.com/v1/leaderboards.schema.json", "SortOrder": "asc", "UpdateType": "keepBest", "Name": "leaderboard"}
Now that you have created a leaderboard, you can add scores to it.ugs deploy leaderboard.lb
Optional: Add scores to the leaderboard
You can run the following Cloud Code script to add scores to the leaderboard from the Unity Dashboard. Make sure to regenerate the Player ID token on every test run to generate a score for a new player.JavaScript
const { LeaderboardsApi } = require("@unity-services/leaderboards-1.1");const _ = require("lodash-4.17");module.exports = async ({ params, context, logger }) => { const leaderboardsApi = new LeaderboardsApi({ accessToken: context.accessToken }); const leaderboardID = "leaderboard"; var randomScore = _.random(1, 100); try { await leaderboardsApi.addLeaderboardPlayerScore(context.projectId, leaderboardID, context.playerId, { score: randomScore }); } catch (err) { logger.error("Failed to add score to the leaderboard", { "error.message": err.message }); }};
Set up Cloud Code
To use Triggers, you should define a Cloud Code module or a Cloud Code script. The module or script is executed when a trigger is fired. The sample below integrates Leaderboards and Cloud Save with Cloud Code to reward the top five players from the leaderboard with a seasonal trophy.Cloud Code C# module
Define aSchedulerHelloWorldkeyvalueRewardPlayersDeploy 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.Apis;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCode.Shared;using Unity.Services.CloudSave.Model;using Unity.Services.Leaderboards.Model;namespace SchedulerHelloWorld;public class SchedulerHelloWorld{ private const string LeaderboardId = "leaderboard"; private readonly ILogger<SchedulerHelloWorld> _logger; public SchedulerHelloWorld(ILogger<SchedulerHelloWorld> logger) { _logger = logger; } [CloudCodeFunction("RewardPlayers")] public async Task RewardPlayers(IExecutionContext ctx, IGameApiClient gameApiClient, string key, string value) { var top5Players = await GetTop5(ctx, gameApiClient); foreach (var score in top5Players) { try { var response = await gameApiClient.CloudSaveData.SetItemAsync(ctx, ctx.ServiceToken, ctx.ProjectId, score.PlayerId, new SetItemBody(key, value)); _logger.LogInformation("Data saved successfully"); } catch (ApiException e) { _logger.LogError( "Failed to record data for playerId {playerId}. Error: {Error}", score.PlayerId, e.Message); throw new Exception($"Failed to record data for playerId {score.PlayerId}. Error: {e.Message}"); } } } [CloudCodeFunction("GetTopPlayers")] public async Task<List<LeaderboardEntry>> GetTop5(IExecutionContext ctx, IGameApiClient gameApiClient) { try { var results = await gameApiClient.Leaderboards.GetLeaderboardScoresAsync(ctx, ctx.ServiceToken, new Guid(ctx.ProjectId), LeaderboardId, null, 5); return results.Data.Results; } catch (ApiException e) { _logger.LogError(e, "Failed to get top players for leaderboard: {LeaderboardId}. Error: {Error}", LeaderboardId, e.Message); throw new Exception($"Failed to get top players for leaderboard: {LeaderboardId}. Error: {e.Message}"); } } public class ModuleConfig : ICloudCodeSetup { public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton(GameApiClient.Create()); } }}
Cloud Code JavaScript script
You can achieve the same outcome by creating a Cloud Code script. Create aSchedulerHelloWorldkeyvalueJavaScript
Publish the script. Refer to Deploying Hello World to learn how to deploy a script.const { DataApi } = require("@unity-services/cloud-save-1.4");const { LeaderboardsApi } = require("@unity-services/leaderboards-1.1");module.exports = async ({ params, context, logger }) => { // Get top 5 players from the Leaderboard const leaderboardId = "my-leaderboard"; const leaderboardsApi = new LeaderboardsApi(context); const cloudSaveApi = new DataApi(context); let result; try { result = await leaderboardsApi.getLeaderboardScores(context.projectId, leaderboardId, 0, 5); } catch (err) { logger.error("Failed to retrieve players from the leaderboard", { "error.message": err.message }); throw err; } // Set Cloud Save data for every player const promises = result.data.results.map(async (score) => { try { await cloudSaveApi.setItem(context.projectId, score.playerId, { key: params.key, value: params.value, }); } catch (err) { logger.error("Failed to update Cloud Save data", { "error.message": err.message }, { affectedPlayerId: score.playerId }); return; } }); await Promise.all(promises);};
Schedule an event
After you have defined your Cloud Code script or module, you can create a schedule to determine when the top five players are rewarded with a trophy. The sample below defines a one-time schedule that grant players a seasonal trophy. Run thenew-fileUpdate theugs scheduler new-file schedule-config
schedule-config.schedThe{ "$schema": "https://ugs-config-schemas.unity3d.com/v1/schedules.schema.json", "Configs": { "grant-trophy": { "EventName": "trophy-for-top-5", "Type": "one-time", "Schedule": "2024-08-28T00:00:00Z", "PayloadVersion": 1, "Payload": "{\"key\": \"seasonal-trophy\", \"value\": \"2024-08-28\"}" } }}
payloadscheduleYou should get a response similar to the following:ugs deploy schedule-config.sched
Now you have a schedule that triggers an event at a specific time. However, the events are not yet connected to your Cloud Code script or module.Deployed:schedule-config.sched
Configure a trigger
To connect your Cloud Code resource to the schedule, create a trigger. The trigger executes the Cloud Code module or script when the event is fired, for example, when the schedule is triggered. Run thenew-fileIf you created a Cloud Code module, update theugs triggers new-file triggers-config
triggers-config.trIf you created a Cloud Code script, update the{ "$schema": "https://ugs-config-schemas.unity3d.com/v1/triggers.schema.json", "Configs": [ { "Name": "trophy-reward", "EventType": "com.unity.services.scheduler.trophy-for-top-5.v1", "ActionUrn": "urn:ugs:cloud-code:SchedulerHelloWorld/RewardPlayers", "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": "trophy-reward", "EventType": "com.unity.services.scheduler.trophy-for-top-5.v1", "ActionUrn": "urn:ugs:cloud-code:SchedulerHelloWorld", "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 the event is fired.Deployed:triggers-config.tr
Validate the result
To validate the result, you can inspect the top players before and after the event is fired.- Navigate to the Unity Dashboard.
- Select Products > Leaderboards.
- Select the Overview section.
- Select the leaderboard.
leaderboard - Select the Entries tab.
- Note down one of the top player IDs.
- From the Unity Dashboard, select Products > Player Management.
- In the search field, enter the player ID you noted down earlier and select Find Player.
- Navigate to the Cloud Save > Data section.
- You should find the key with the value
seasonal-trophy.2023-08-28
- In the Unity Dashboard, open Cloud Code.
- Select Logs.
SchedulerHelloWorld