使用示例:祝玩家新年快乐
Send a push notification to all users on January 1st at 00:00:00 UTC wishing them a happy new year.
阅读时间5 分钟最后更新于 1 个月前
此示例演示如何设置一个计划,在 1 月 1 日 00:00:00 UTC 向所有用户发送推送通知,祝他们新年快乐。
先决条件
必须首先创建具有所需访问角色的服务帐户,并配置 UGS CLI。使用服务帐户进行身份验证
在调用 Scheduling 和 Triggers 服务之前,必须使用服务帐户进行身份验证。- 导航到 Unity Cloud Dashboard。
- 选择 Administration(管理)> Service Accounts(服务帐户)。
- 选择 New(新建) 按钮并输入服务帐户的名称和描述。
- 选择 Create(创建)。
- 选择 Manage product roles(管理产品角色)。
- 将以下角色添加到服务帐户:
- 从 LiveOps 下拉选单中,选择 Triggers Configuration Editor(Triggers 配置编辑者)、Triggers Configuration Viewer(Triggers 配置查看者)、Scheduler Configuration Editor(Scheduler 配置编辑者) 和 Scheduler Configuration Viewer(Scheduler 配置查看者)。
- 从 Admin(管理)下拉选单中,选择 Unity Environments Viewer(Unity 环境查看者)。
- 从 LiveOps 下拉选单中,选择 Triggers Configuration Editor(Triggers 配置编辑者)、Triggers Configuration Viewer(Triggers 配置查看者)、Scheduler Configuration Editor(Scheduler 配置编辑者) 和 Scheduler Configuration Viewer(Scheduler 配置查看者)。
- 选择 Save(保存)。
- 选择 Add Key(添加密钥)。
- 使用 base64 编码方式对 Key ID(密钥 ID) 和 Secret key(密钥) 进行编码。格式为“key_id:secret_key”。请记下此值。
配置 UGS CLI
按照以下步骤操作以开始使用 UGS CLI:- 安装 UGS CLI。
-
按如下方式配置 Project ID 和环境:
ugs config set project-id <your-project-id>
ugs config set environment-name <your-environment-name> - 使用您先前创建的服务帐户进行身份验证。请参阅接受身份验证。
设置 Cloud Code
定义一个模块终端,向分数被超过的玩家发送推送通知。 创建一个包含如下内容的WishHappyNewYear部署该模块。 请参阅部署 Hello World 以了解如何部署模块。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()); }}
计划事件
定义 Cloud Code 模块后,您可以创建一个计划,在 1 月 1 日 00:00:00 UTC 向所有用户发送推送通知,祝他们新年快乐。 运行new-file使用以下配置来更新ugs scheduler new-file schedule-config
schedule-config.sched使用 UGS CLI 工具部署此配置:{ "$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\"}" } }}
正确的响应类似于以下内容:ugs deploy schedule-config.sched
Deployed:schedule-config.sched
配置触发器
要将 Cloud Code 模块关联到计划事件,请创建触发器。此触发器会在 1 月 1 日 00:00:00 UTC 触发事件时执行 Cloud Code 模块。 运行new-file使用以下配置来更新ugs triggers new-file triggers-config
triggers-config.tr使用 UGS CLI 工具部署此配置:{ "$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" } ]}
您应该会看到类似于以下内容的响应:ugs deploy triggers-config.tr
现在,您有了一个触发器会在 1 月 1 日 00:00:00 UTC 触发计划事件时执行 Cloud Code 模块函数。Deployed:triggers-config.tr
验证结果
要验证结果,请设置一个 Unity 项目来订阅推送消息。先决条件
要订阅推送消息,必须先安装 Cloud Code SDK,并将 Unity Gaming Services(Unity 游戏服务)项目关联到 Unity 编辑器。关联项目
将 Unity Gaming Services(Unity 游戏服务)项目与 Unity 编辑器关联。您可以在 Unity Cloud Dashboard 中找到您的 UGS Project ID。- 在 Unity 编辑器中,选择 Edit(编辑)> Project Settings...(项目设置...)> Services(服务)。
- 关联您的项目。
- 如果项目没有 Unity Project ID:
- 选择 Create a Unity Project ID(创建 Unity Project ID)> Organizations(组织),然后从下拉菜单中选择一个组织。
- 选择 Create project ID(创建 Project ID)。
- 如果已有 Unity Project ID:
- 选择 Use an existing Unity project ID(使用现有 Unity Project ID)。
- 从下拉菜单中选择组织和项目。
- 选择 Link project ID(关联 Project ID)。
UnityEditor.CloudProjectSettings.projectIdSDK 安装
要安装适用于 Unity 编辑器的最新 Cloud Code 包,请执行以下操作:- 在 Unity 编辑器中,打开 Window(窗口)> Package Manager(包管理器)。
- 在 Package Manager(包管理器)中,选择 Unity Registry(Unity 注册表) 列表视图。
- 搜索 或在列表中找到 Cloud Code 包。
com.unity.services.cloudcode - 选择包,然后单击 Install(安装)。
创建 Monobehaviour 脚本
设置MonobehaviourMonoBehaviour在 Unity 编辑器中运行该模块时,您应该会看到一条推送消息: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"}