Use case sample: Wish players a happy new year
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
Note: You can only use push messages with Cloud Code modules.
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 Cloud Dashboard.
- Select Administration > 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, 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.
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.
Set up Cloud Code
Define a module endpoint that sends a push notification to the player whose score was beaten.
Create a WishHappyNewYear
module function with contents as below:
C#
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());
}
}
Deploy the module.
Refer to Deploying Hello World to learn how to deploy a module.
Note: If you are deploying the module using the UGS CLI, don't forget to add additional Service Account role of Cloud Code Editor
.
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 the new-file
command to create a schedule configuration locally:
ugs scheduler new-file schedule-config
Update the schedule-config.sched
file with the following configuration:
{
"$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\"}"
}
}
}
Deploy the configuration using the UGS CLI tool:
ugs deploy schedule-config.sched
The correct response is similar to the following:
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 the new-file
command to create a trigger configuration locally:
ugs triggers new-file triggers-config
Update the triggers-config.tr
file with the following configuration:
{
"$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"
}
]
}
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 module function when the scheduler event is fired at 00:00:00 UTC on January 1st.
Validate the result
To validate the result, set up a Unity project that subscribes to push messages.
Note: To test the event, you might want change the timestamp in the one-time
field to a closer time.
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 Cloud 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.
Your Unity Project ID appears, and the project is now linked to Unity services. You can also access your project ID in a Unity Editor script using UnityEditor.CloudProjectSettings.projectId
.
SDK 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
com.unity.services.cloudcode
, or locate the Cloud Code package in the list. - Select the package, then click Install.
Check Unity - Manual: Package Manager window to familiarize yourself with the Unity Package Manager interface.
Subscribing to messages is available with Cloud Code SDK version 2.4.0+.
Create a Monobehaviour
script
Set up a Monobehaviour
script to subscribe to project-level messages.
Refer to Send push messages for more information.
You can use the sample code below for your MonoBehaviour
script:
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);
}
}
You should encounter a push message sent when the module runs in the Unity Editor:
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"
}