# 使用示例：祝玩家新年快乐

> Send a push notification to all users on January 1st at 00:00:00 UTC wishing them a happy new year.

此示例演示如何设置一个计划，在 1 月 1 日 00:00:00 UTC 向所有用户发送推送通知，祝他们新年快乐。

> **Note:**
>
> **注意：** 只能将[推送消息](/cloud-code/modules/how-to-guides/push-messages.md)与 Cloud Code 模块配合使用。

## 先决条件##prerequisites

必须首先创建具有所需访问角色的服务帐户，并配置 [UGS CLI](https://services.docs.unity.com/guides/ugs-cli/latest/general/get-started/install-the-cli/)。

### 使用服务帐户进行身份验证##authenticate-using-a-service-account

在调用 Scheduling 和 Triggers 服务之前，必须使用服务帐户进行身份验证。

1. 导航到 [Unity Dashboard](https://cloud.unity.com)。
2. 选择 **Administration（管理）**> **Service Accounts（服务帐户）**。
3. 选择 **New（新建）** 按钮并输入服务帐户的名称和描述。
4. 选择 **Create（创建）**。

添加产品角色并创建密钥：

1. 选择 **Manage product roles（管理产品角色）**。
2. 将以下角色添加到服务帐户：
   * 从 LiveOps 下拉选单中，选择 **Triggers Configuration Editor（Triggers 配置编辑者）**、**Triggers Configuration Viewer（Triggers 配置查看者）**、**Scheduler Configuration Editor（Scheduler 配置编辑者）** 和 **Scheduler Configuration Viewer（Scheduler 配置查看者）**。
   * 从 Admin（管理）下拉选单中，选择 **Unity Environments Viewer（Unity 环境查看者）**。
3. 选择 **Save（保存）**。
4. 选择 **Add Key（添加密钥）**。
5. 使用 base64 编码方式对 **Key ID（密钥 ID）** 和 **Secret key（密钥）** 进行编码。格式为“key\_id:secret\_key”。请记下此值。

如需了解更多信息，请参阅[身份验证](../../authentication)。

### 配置 UGS CLI##configure-the-ugs-cli

按照以下步骤操作以开始使用 UGS CLI：

1. [安装 UGS CLI](https://services.docs.unity.com/guides/ugs-cli/latest/general/get-started/install-the-cli/)。

2. 按如下方式配置 Project ID 和环境：
   `ugs config set project-id <your-project-id>`
   `ugs config set environment-name <your-environment-name>`

3. 使用您先前创建的服务帐户进行身份验证。请参阅[接受身份验证](https://services.docs.unity.com/guides/ugs-cli/latest/general/get-started/get-authenticated/)。

## 设置 Cloud Code##set-up-cloud-code

定义一个模块终端，向分数被超过的玩家发送推送通知。

创建一个包含如下内容的 `WishHappyNewYear` 模块函数：

```csharp
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());

    }
}
```

部署该模块。

请参阅[部署 Hello World](/cloud-code/modules/getting-started.md#deploy-the-module) 以了解如何部署模块。

> **Note:**
>
> **注意：** 如果您使用 UGS CLI 来部署模块，请不要忘记添加额外的服务帐户角色 `Cloud Code Editor`。

## 计划事件##schedule-an-event

定义 Cloud Code 模块后，您可以创建一个计划，在 1 月 1 日 00:00:00 UTC 向所有用户发送推送通知，祝他们新年快乐。

运行 `new-file` 命令在本地创建计划配置：

```bash
ugs scheduler new-file schedule-config
```

使用以下配置来更新 `schedule-config.sched` 文件：

```json
{
  "$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 CLI 工具部署此配置：

```bash
ugs deploy schedule-config.sched
```

正确的响应类似于以下内容：

```text
Deployed:
    schedule-config.sched
```

## 配置触发器##configure-a-trigger

要将 Cloud Code 模块关联到计划事件，请创建触发器。此触发器会在 1 月 1 日 00:00:00 UTC 触发事件时执行 Cloud Code 模块。

运行 `new-file` 命令在本地创建触发器配置：

```bash
ugs triggers new-file triggers-config
```

使用以下配置来更新 `triggers-config.tr` 文件：

```json
{
  "$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 CLI 工具部署此配置：

```bash
ugs deploy triggers-config.tr
```

您应该会看到类似于以下内容的响应：

```text
Deployed:
    triggers-config.tr
```

现在，您有了一个触发器会在 1 月 1 日 00:00:00 UTC 触发计划事件时执行 Cloud Code 模块函数。

## 验证结果##validate-the-result

要验证结果，请设置一个 Unity 项目来订阅推送消息。

> **Note:**
>
> **注意：** 要测试事件，可能需要将 `one-time` 字段中的时间戳更改为更近的时间。

### 先决条件##prerequisites

要订阅推送消息，必须先安装 Cloud Code SDK，并将 [Unity Gaming Services（Unity 游戏服务）项目](/cloud/projects.md)关联到 Unity 编辑器。

#### 关联项目##link-project

将 [Unity Gaming Services（Unity 游戏服务）项目](/cloud/projects.md)与 Unity 编辑器关联。您可以在 [Unity Dashboard](https://cloud.unity.com) 中找到您的 UGS Project ID。

1. 在 Unity 编辑器中，选择 **Edit（编辑）**> **Project Settings...（项目设置...）**> **Services（服务）**。

2. 关联您的项目。

* 如果项目没有 Unity Project ID：

1. 选择 **Create a Unity Project ID（创建 Unity Project ID）**> **Organizations（组织）**，然后从下拉菜单中选择一个组织。
2. 选择 **Create project ID（创建 Project ID）**。

* 如果已有 Unity Project ID：

1. 选择 **Use an existing Unity project ID（使用现有 Unity Project ID）**。
2. 从下拉菜单中选择组织和项目。
3. 选择 **Link project ID（关联 Project ID）**。

此时将显示您的 Unity Project ID，并且项目现在已关联到 Unity 服务。此外，还可以使用 `UnityEditor.CloudProjectSettings.projectId` 在 Unity 编辑器脚本中访问您的 Project ID。

#### SDK 安装##sdkinstallation

要安装适用于 Unity 编辑器的最新 Cloud Code 包，请执行以下操作：

1. 在 Unity 编辑器中，打开 **Window（窗口）**> **Package Manager（包管理器）**。
2. 在 Package Manager（包管理器）中，选择 **Unity Registry（Unity 注册表）** 列表视图。
3. 搜索 `com.unity.services.cloudcode` 或在列表中找到 Cloud Code 包。
4. 选择包，然后单击 **Install（安装）**。

> **Note:**
>
> 请查看 [Unity - 手册：Package Manager（包管理器）窗口](https://docs.unity3d.com/Manual/upm-ui.html)，熟悉 Unity Package Manager（包管理器）界面。

> **Note:**
>
> 从 Cloud Code SDK 版本 2.4.0 开始支持订阅消息。

### 创建 `Monobehaviour` 脚本##create-a-monobehaviour-script

设置 `Monobehaviour` 脚本以订阅项目级消息。

如需了解更多信息，请参阅[发送推送消息](/cloud-code/modules/how-to-guides/push-messages.md)。

您可以将以下示例代码用于您的 `MonoBehaviour` 脚本：

```csharp
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);
        }
}
```

在 Unity 编辑器中运行该模块时，您应该会看到一条推送消息：

```yaml
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"
}
```
