# 使用の準備

> 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 エディターにリンクする必要があります。UGS プロジェクト ID は Unity Dashboard にあります。

1. Unity エディターで、**Edit** (編集) > **Project Settings** (プロジェクト設定) > **Services** (サービス) の順に選択します。

2. プロジェクトをリンクします。

   * プロジェクトに Unity プロジェクト ID がない場合:

     1. **Create a Unity Project ID** (Unity プロジェクト ID の作成) > **Organizations** (組織) の順に選択し、ドロップダウンメニューから組織を選択します。
     2. **Create project ID** (プロジェクト ID を作成) を選択します。

   * 既存の Unity プロジェクト ID がある場合:

     1. **Use an existing Unity project ID** (既存の Unity プロジェクト ID を使用) を選択します。
     2. ドロップダウンメニューから組織とプロジェクトを選択します。
     3. **Link project ID** (プロジェクト ID をリンク) を選択します。

Unity プロジェクト ID が表示され、プロジェクトが Unity サービスにリンクされました。また、`UnityEditor.CloudProjectSettings.projectId` を使用して Unity エディタースクリプトのプロジェクト 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

Cloud Code SDK は、[Authentication SDK](#authentication) にサインインした後で使用する準備ができます。Cloud Code SDK では、[Unity Dashboard](https://cloud.unity.com/cloud-code) の Cloud Code ページで 1 つ以上のクラウドスクリプトを作成する必要があります。次に、任意の Cloud Code メソッドを呼び出して、データの操作を開始できます。

Cloud Code SDK の使用を準備するには、以下を行います。

1. Cloud Code サービスダッシュボードページを介してサービスが有効になっていることを確認します。
2. Cloud Code と Authentication SDK の両方をインストールしたことを確認します。
3. **Edit** (編集) > **Project Settings...** (プロジェクト設定...) > **Services** (サービス) を選択して、Unity エディター内からクラウドプロジェクトにサインインします。
4. Unity エディターで新しい C# Monobehaviour スクリプトを作成します。Unity マニュアルの [スクリプトの作成と使用](https://docs.unity3d.com/Manual/CreatingAndUsingScripts.html) を参照してください。
5. スクリプトで、await `UnityServices.InitializeAsync()` を使用して Core SDK を初期化します。
6. スクリプトで、[Authentication SDK](#authentication) を初期化します。

> **Note:**
>
> **ノート**: プレイヤーには、Cloud Code サービスにアクセスするための有効なプレイヤー ID とアクセストークンが必要です。いずれかの 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 サービスにアクセスするための有効なプレイヤー ID とアクセストークンが必要です。[認証](../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. プロジェクト 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 を使用します。         |
| [外部サービスとのインテグレーション](./how-to-guides/external-services-integration.md)                     | パブリックインターネットエンドポイントを呼び出します。                    |
| [利用可能なライブラリ](./reference/available-libraries.md)                                          | Cloud Code スクリプトに使用可能なライブラリを確認します。             |
| [ユースケース](./use-cases.md)                                                                  | Cloud Code を他のサービスと統合するにはユースケースのサンプルを参照してください。 |
