Use case sample: Wish players a happy new year
Send a push notification to all users on January 1st at 00:00:00 UTC wishing them a happy new year.
Read time 4 minutesLast updated 18 hours ago
This sample demonstrates how to set up a schedule to send a push notification to all users wishing them a happy new year at 00:00:00 UTC on January 1st
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 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 and Scheduler Configuration Viewer .
- From the Admin dropdown, select Unity Environments Viewer.
- From the LiveOps dropdown, select Triggers Configuration Editor, Triggers Configuration Viewer, Scheduler Configuration Editor and Scheduler 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.
Set up Cloud Code
Define a module endpoint that sends a push notification to the player whose score was beaten. Create aWishHappyNewYearDeploy 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;namespace WishHappyNewYear;public class HappyNewYear{ private readonly ILogger<HappyNewYear> _logger; public HappyNewYear(ILogger<HappyNewYear> logger) { _logger = logger; } [CloudCodeFunction("SendProjectMessage")] public async Task SendProjectMessage(IExecutionContext context, PushClient pushClient, string message, string messageType) { try { await pushClient.SendProjectMessageAsync(context, message, messageType); } catch (ApiException e) { _logger.LogError("Failed to send project message. Error: {Error}", e.Message); throw new Exception($"Failed to send project message. Error: {e.Message}"); } }}public class ModuleConfig : ICloudCodeSetup{ public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton(PushClient.Create()); }}
Schedule an event
After you have defined your Cloud Code module, you can create a schedule to send a push notification to all users wishing them a happy new year at 00:00:00 UTC on January 1st. Run thenew-fileUpdate theugs scheduler new-file schedule-config
schedule-config.schedDeploy the configuration using the UGS CLI tool:{ "$schema": "https://ugs-config-schemas.unity3d.com/v1/schedules.schema.json", "Configs": { "wish-happy-new-year": { "EventName": "send-announcement", "Type": "one-time", "Schedule": "2025-01-01T00:00:00Z", "PayloadVersion": 1, "Payload": "{\"message\": \"Happy New Year!\", \"messageType\": \"HappyNewYear\"}" } }}
The correct response is similar to the following:ugs deploy schedule-config.sched
Deployed:schedule-config.sched
Configure a trigger
To connect your Cloud Code module to the scheduler event, create a trigger. The trigger executes the Cloud Code module when the event is fired at 00:00:00 UTC on January 1st. Run thenew-fileUpdate theugs triggers new-file triggers-config
triggers-config.trDeploy the configuration using the UGS CLI tool:{ "$schema": "https://ugs-config-schemas.unity3d.com/v1/triggers.schema.json", "Configs": [ { "Name": "happy-new-year", "EventType": "com.unity.services.scheduler.send-announcement.v1", "ActionUrn": "urn:ugs:cloud-code:WishHappyNewYear/SendProjectMessage", "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 module function when the scheduler event is fired at 00:00:00 UTC on January 1st.Deployed:triggers-config.tr
Validate the result
To validate the result, set up a Unity project that subscribes to push messages.Prerequisites
To subscribe to push messages, you must first install the Cloud Code SDK and link your Unity Gaming Services project to the Unity Editor.Link project
Link your Unity Gaming Services project with the Unity Editor. You can find your UGS project ID in the Unity Dashboard.- In the Unity Editor, select Edit > Project Settings > Services.
- Link your project.
- If your project doesn't have a Unity project ID:
- Select Create a Unity Project ID > Organizations, then select an organization from the dropdown menu.
- Select Create project ID.
- If you have an existing Unity project ID:
- Select Use an existing Unity project ID.
- Select an organization and a project from the dropdown menus.
- Select Link project ID.
UnityEditor.CloudProjectSettings.projectIdSDK installation
To install the latest Cloud Code package for Unity Editor:- In the Unity Editor, open Window > Package Manager.
- In the Package Manager, select the Unity Registry list view.
- Search for , or locate the Cloud Code package in the list.
com.unity.services.cloudcode - Select the package, then click Install.
Create a Monobehaviour
script
Set up a MonobehaviourMonobehaviourMonoBehaviourYou should encounter a push message sent when the module runs in the Unity Editor:using System;using System.Threading.Tasks;using Newtonsoft.Json;using Unity.Services.Authentication;using Unity.Services.CloudCode;using Unity.Services.CloudCode.Subscriptions;using Unity.Services.Core;using UnityEngine;namespace CloudCode{ public class CloudCodePushExample : MonoBehaviour { async void Start() { await UnityServices.InitializeAsync(); await AuthenticationService.Instance.SignInAnonymouslyAsync(); Debug.Log(AuthenticationService.Instance.PlayerId); await SubscribeToProjectMessages(); } // This method creates a subscription to project messages and logs out the messages received, // the state changes of the connection, when the player is kicked and when an error occurs. Task SubscribeToProjectMessages() { var callbacks = new SubscriptionEventCallbacks(); callbacks.MessageReceived += @event => { Debug.Log(DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK")); Debug.Log($"Got project subscription Message: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; callbacks.ConnectionStateChanged += @event => { Debug.Log($"Got project subscription ConnectionStateChanged: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; callbacks.Kicked += () => { Debug.Log($"Got project subscription Kicked"); }; callbacks.Error += @event => { Debug.Log($"Got project subscription Error: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; return CloudCodeService.Instance.SubscribeToProjectMessagesAsync(callbacks); }}
Got project subscription Message:{ "data_base64": <BASE64-ENCODED-DATA>, "time": "2023-09-27T16:01:46.468321794Z", "message": "Happy new year!", "specversion": "1.0", "id": <ID>, "source": "https://cloud-code.service.api.unity.com", "type": "com.unity.services.cloud-code.push.v1", "projectid": <PROJECT-ID>, "environmentid": <ENVIRONMENT-ID>, "correlationid": <CORRELATION-ID>, "messagetype": "announcement",}