# 开始使用

> Follow this workflow to create a JavaScript script that can prevent cheating and execute code asynchronously.

本节介绍创建 JavaScript 脚本所需的所有步骤。

## 部署 Hello World##deploying-hello-world

Cloud Code 有助于为游戏运行自定义服务器端代码。您可以在 Cloud Code 服务器上运行代码以防止作弊，还可异步执行代码以响应服务器端事件。您可以在 Cloud Code 中定义一个简单的“hello world”脚本来测试服务。

### 先决条件##prerequisites

在创建下面的脚本之前，请确保按照以下步骤操作。

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

要使用 Cloud Code 服务，必须将您的 UGS 项目与 Unity 编辑器关联。您可以在 Unity Dashboard 中找到您的 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（安装）**。

请查看 [Package Manager（包管理器）](https://docs.unity3d.com/Manual/upm-ui.html)文档，了解更多信息。

如需详细的 SDK 文档，请参阅 [Cloud Code SDK API](https://docs.unity3d.com/Packages/com.unity.services.cloudcode@latest/index.html?subfolder=/api/Unity.Services.CloudCode)。

#### SDK 设置##sdk-setup

使用 [Authentication SDK](#authentication) 登录后，即可使用 Cloud Code SDK。Cloud Code SDK 需要在 [Unity Dashboard](https://cloud.unity.com/cloud-code) 的 Cloud Code 页面中创作一个或多个云脚本。然后，您可以调用任何 Cloud Code 方法，开始处理您的数据。

开始使用 Cloud Code SDK：

1. 确保通过 Cloud Code 服务后台页面启用该服务。
2. 确保 Cloud Code SDK 和 Authentication SDK 均已安装。
3. 在 Unity 编辑器中选择 **Edit（编辑）**> **Project Settings...（项目设置...）**> **Services（服务）** 登录到您的云项目。
4. 在 Unity 编辑器中创建新的 C# Monobehaviour 脚本。请参阅 Unity 手册中的[创建和使用脚本](https://docs.unity3d.com/Manual/CreatingAndUsingScripts.html)。
5. 在脚本中，使用 await `UnityServices.InitializeAsync()` 初始化 Core SDK。
6. 在脚本中，初始化 [Authentication SDK](#authentication)。

> **Note:**
>
> **注意：** 玩家必须拥有有效的玩家 ID 和访问令牌才能访问 Cloud Code 服务。在使用任何 Cloud Code API 之前，您必须使用 Authentication SDK 对玩家进行身份验证。为此，您可以使用以下代码片段进行匿名身份验证，或查看 [Authentication](../modules/how-to-guides/authentication) SDK 的文档，了解更多详细信息和其他登录方法。

*C#*

```cs
await AuthenticationService.Instance.SignInAnonymouslyAsync();
```

如需有关设置脚本的示例和信息，请参阅[从 Unity Runtime 调用](../modules/how-to-guides/run-modules/unity-runtime)。

#### 身份验证##authentication

应用程序通常需要了解用户的身份信息，以此为游戏开发者和玩家提供多样化的功能和服务，确保每项交互的安全性和一致性。每个玩家必须拥有有效的玩家 ID 和访问令牌才能访问 Cloud Code 服务。请参阅[身份验证](../modules/how-to-guides/authentication)。

### 编写您的第一个脚本##writing-your-first-script

使用 [Unity Dashboard](https://cloud.unity.com) 创建一个具有 `string` 类型的 `name` 参数的新脚本。如需更详细的说明，请参阅[使用 Unity Dashboard 编写脚本](./how-to-guides/write-scripts/unity-dashboard.md)。

然后，您可以使用以下代码片段作为您的代码。

*JavaScript*

```js
module.exports = async ({ params, logger }) => {
  const name = params.name;
  const message = `Hello, ${name}. Welcome to Cloud Code!`

  logger.debug(message);
  return {
    welcomeMessage: message
  };
};
```

保存更改并发布您的脚本。发布后，您可以使用其中一个 SDK 终端从项目调用 Cloud Code 脚本，如以下示例所示。如需更详细的说明，请查看[从 Unity Runtime 调用](./how-to-guides/run-scripts/unity-runtime.md)。

*C#*

```cs
using System.Collections.Generic;
using Unity.Services.Authentication;
using Unity.Services.CloudCode;
using Unity.Services.Core;
using UnityEngine;

/*
 * Note: You must have a published script to use the Cloud Code SDK.
 * You can publish a script from the Unity Dashboard - https://cloud.unity.com
 */
public class CloudCodeExample : MonoBehaviour
{
    /*
     * CloudCodeResponse represents the response from the script, used for deserialization.
     * In this example, the script returns a JSON in the format
     * {"welcomeMessage": "Hello, arguments['name']. Welcome to Cloud Code!"}
     */
    class CloudCodeResponse
    {
        public string welcomeMessage;
    }

    /*
     * Initialize all Unity Services and Sign In an anonymous player.
     * You can perform this operation in a more centralized spot in your project
     */
    public async void Awake()
    {
        await UnityServices.InitializeAsync();
        await AuthenticationService.Instance.SignInAnonymouslyAsync();
    }

    /*
     * Populate a Dictionary<string,object> with the arguments and invoke the script.
     * Deserialize the response into a CloudCodeResponse object
     */
    public async void OnClick()
    {
        var arguments = new Dictionary<string, object> { { "name", "Unity" } };
        var response = await CloudCodeService.Instance.CallEndpointAsync<CloudCodeResponse>("hello-world", arguments);
    }
}
```

### 部署 Cloud Code 脚本##deploy-a-cloud-code-script

要使游戏客户端能够访问您的脚本终端，您必须将脚本部署到 Cloud Code 服务。

请参阅[编写脚本](./how-to-guides/write-scripts.md)以了解有关脚本部署的更多信息。

#### 配置 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. 为服务帐户配置 [Cloud Code](https://services.docs.unity.com/docs/service-account-auth/index.html#cloud-code-editor) 和[环境管理](https://services.docs.unity.com/docs/service-account-auth/index.html#unity-environments-admin)所需的角色。请参阅[接受身份验证](https://services.docs.unity.com/guides/ugs-cli/latest/general/get-started/get-authenticated/)。

#### 部署该脚本##deploy-the-script

运行以下命令：

`ugs deploy <path-to-js-file>`

## 后续步骤##next-steps

按照部署第一个脚本后的后续步骤操作。

| **主题**                                      | **描述**                |
| ------------------------------------------- | --------------------- |
| [测试运行脚本](./how-to-guides/test-run.md)       | 在将更改发布到游戏客户端之前测试您的脚本。 |
| [脚本结构](./how-to-guides/script-structure.md) | 熟悉脚本结构。               |
| [与 CI/CD 集成](./how-to-guides/automation.md) | 将脚本集成到 CI/CD 管线中。     |

### 集成##integration

Cloud Code 与其他服务结合使用时功能更强大。

| **主题**                                                                                | **描述**                                        |
| ------------------------------------------------------------------------------------- | --------------------------------------------- |
| [与其他 Unity 服务集成](./how-to-guides/unity-services-integration.md)                       | 编写调用其他 Unity 服务的 Cloud Code 脚本。               |
| [Cloud Code Services SDK 文档](https://cloud-code-sdk-documentation.cloud.unity3d.com/) | 在脚本中使用其他 Unity Gaming Services（Unity 游戏服务）服务。 |
| [与外部服务集成](./how-to-guides/external-services-integration.md)                           | 调用公共互联网终端。                                    |
| [可用库](./reference/available-libraries.md)                                             | 查看哪些库可用于 Cloud Code 脚本。                       |
| [用例](./use-cases.md)                                                                  | 参阅使用示例以将 Cloud Code 与其他服务集成。                  |
