# ユースケースサンプル: 新規にサインアップしたプレイヤーのデフォルト設定値での初期化

> Initialize new players with default values in Cloud Save when they first sign up.

ユースケースサンプルは、Triggers を使用して、新しいプレイヤーが最初にサインアップしたときに Cloud Save のデフォルトの健全性とスタミナ値で初期化する方法を示します。[Authentication サービス](/authentication/how-authentication-works.md) によって発行される `signedUp` イベントを使用し、値を [Cloud Save](/cloud-save.md) に保存します。

## 前提条件##prerequisites

最初に、必要なアクセスロールでサービスアカウントを作成し、[UGS CLI](https://services.docs.unity.com/guides/ugs-cli/latest/general/get-started/install-the-cli/) を設定する必要があります。

### サービスアカウントを使用した認証##authenticate-using-a-service-account

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 設定閲覧者) を選択します。
   * Admin (管理者) ドロップダウンから **Unity Environments Viewer** (Unity 環境閲覧者) を選択します。
3. **Save** (保存) を選択します。
4. **Add Key** (キーの追加) を選択します。
5. base64 エンコードを使用して **Key ID** (キー ID) と **Secret key** (秘密鍵) をエンコードします。形式は "key\_id:secret\_key" です。この値をメモしておきます。

詳細については、[Authentication](../../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. プロジェクト 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/) を参照してください。

## `signed-up` イベントを調べる##examine-the-signed-up-event

Authentication サービスは、プレイヤーが作成されたときに `signed-up` イベントを発行します。イベントペイロードは以下のようになります。

```json
{
  "playerId": "string",
  "providerId": "string",
  "createdAt": "string"
}
```

イベントペイロードは、パラメーターとして Cloud Code に渡されます。

詳細については、[認証: サインアップ](/triggers/manage-events/supported-ugs-events.md#signed-up) を参照してください。

## Cloud Code の設定##set-up-cloud-code

Cloud Save を呼び出すモジュールエンドポイントまたはスクリプトを定義して、新規に認証されたプレイヤーをデフォルトの健全性およびスタミナ値で初期化します。

### Cloud Code C# モジュール##cloud-code-c-module

以下のようなコンテンツで必須の文字列引数 `playerId` を設定して、`InitializeNewPlayer` モジュール関数を作成します。

```csharp
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Unity.Services.CloudCode.Core;
using Unity.Services.CloudCode.Apis;
using Unity.Services.CloudCode.Shared;
using Unity.Services.CloudSave.Model;

public class ModuleSample
{
    private const string HealthKey = "HEALTH";
    private const string StaminaKey = "STAMINA";
    private const int DefaultValue = 100;

    private readonly ILogger<ModuleSample> _logger;
    public ModuleSample(ILogger<ModuleSample> logger)
    {
        _logger = logger;
    }

    [CloudCodeFunction("InitializeNewPlayer")]
    public async Task InitializeNewPlayer(IExecutionContext ctx, IGameApiClient gameApiClient, string playerId)
    {
        try
        {
            var response = await gameApiClient.CloudSaveData.GetItemsAsync(ctx, ctx.ServiceToken, ctx.ProjectId, playerId, new List<string>() { HealthKey, StaminaKey });
            if (response.Data.Results.Count == 0)
            {
                await gameApiClient.CloudSaveData.SetItemBatchAsync(ctx, ctx.ServiceToken, ctx.ProjectId, playerId,
                    new SetItemBatchBody(new List<SetItemBody>{new (HealthKey, DefaultValue), new (StaminaKey, DefaultValue)}));

                _logger.LogInformation("The player has been initialized with the {HealthKey} and {StaminaKey} keys with values of {DefaultValue}", HealthKey, StaminaKey, DefaultValue);

            }
        } catch (ApiException e)
        {
            _logger.LogError("Failed to initialize player data in Cloud Save. Error: {Error}", e.Message);
            throw new Exception($"Failed to initialize {playerId} data in Cloud Save. Error: {e.Message}");
        }
    }

    public class ModuleConfig : ICloudCodeSetup
    {
        public void Setup(ICloudCodeConfig config)
        {
            config.Dependencies.AddSingleton(GameApiClient.Create());
        }
    }

}
```

モジュールをデプロイします。

モジュールのデプロイ方法を学習するには、[Hello World のデプロイ](/cloud-code/modules/getting-started.md#deploy-the-module) を参照してください。

> **Note:**
>
> **ノート:** UGS CLI を使用してモジュールをデプロイする場合は、`Cloud Code Editor` の追加のサービスアカウントロールを忘れずに追加してください。

### Cloud Code JavaScript スクリプト##cloud-code-javascript-script

以下の内容を使用して、必須の文字列パラメーター `playerId` を加えて `InitializeNewPlayer` スクリプトを作成します。

#### JavaScript##javascript

```javascript
const { DataApi } = require("@unity-services/cloud-save-1.4");

const CLOUD_SAVE_HEALTH_KEY = "HEALTH";
const CLOUD_SAVE_STAMINA_KEY = "STAMINA";
const DEFAULT_VALUE = 100;

module.exports = async ({ params, context, logger }) => {
  const cloudSaveApi = new DataApi(context);

  try {
    // Check if player has been initialized yet
    const cloudSaveGetResponse = await cloudSaveApi.getItems(context.projectId, params.playerId, [CLOUD_SAVE_HEALTH_KEY, CLOUD_SAVE_STAMINA_KEY]);

    if (cloudSaveGetResponse.data.results.length === 0) {
      // Record new values for player
      await cloudSaveApi.setItemBatch(context.projectId, params.playerId, {
        data: [
          {
            key: CLOUD_SAVE_HEALTH_KEY,
            value: DEFAULT_VALUE,
          },
          {
            key: CLOUD_SAVE_STAMINA_KEY,
            value: DEFAULT_VALUE,
          },
        ],
      });

      logger.info(`The player has been initialized with the ${CLOUD_SAVE_HEALTH_KEY} and ${CLOUD_SAVE_STAMINA_KEY} keys with values of ${DEFAULT_VALUE}`, { "affectedPlayerId": params.playerId });
      return;
    }

    logger.info("The player has already been initialized.", { affectedPlayerId: params.playerId });
  } catch (err) {
    logger.error("Failed to update Cloud Save data", { "error.message": err.message }, { "affectedPlayerId": params.playerId });
    throw err;
  }
};

// Uncomment the code below to enable the inline parameter definition
// - Requires Cloud Code JS dev environment setup with NodeJS (https://docs.unity3d.com/Packages/com.unity.services.cloudcode@latest/index.html?subfolder=/manual/Authoring/javascript_project.html)
//
// module.exports.params = {
//   playerId: { type: "String", required: true },
// };
```

> **Note:**
>
> **ノート:** Unity エディターを使用してスクリプトを管理している場合は、スクリプトの下部にあるコードのコメントを外して、必要な `playerId` パラメーターをスクリプト内で宣言できます。スクリプト内パラメーターの管理方法の詳細については、[Unity エディター](/cloud-code/scripts/how-to-guides/write-scripts/unity-editor.md#modify-script-parameters) 内でのスクリプトパラメーターの変更に関するページを参照してください。スクリプトを公開します。

スクリプトのデプロイ方法を学習するには、[Hello World のデプロイ](/cloud-code/scripts/getting-started.md#deploying-hello-world) を参照してください。

> **Note:**
>
> **ノート:** UGS CLI を使用してスクリプトをデプロイする場合は、追加のサービスアカウントロール (`Cloud Code Script Publisher` と `Cloud Code Editor`) を忘れずに追加してください。

## トリガーの設定##configure-a-trigger

Cloud Code リソースを Authentication `signed-up` イベントに接続するには、トリガーを作成します。トリガーは、イベントが発生したとき、例えば新しいプレイヤーがサインアップするたびに、Cloud Code スクリプトまたはモジュールを実行します。

`new-file` コマンドを実行して、トリガー設定をローカルに作成します。

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

Cloud Code スクリプトを作成した場合は、以下の設定で `triggers-config.tr` ファイルを更新します。

```json
{
  "$schema": "https://ugs-config-schemas.unity3d.com/v1/triggers.schema.json",
  "Configs": [
    {
      "Name": "initialize-new-player",
      "EventType": "com.unity.services.player-auth.signed-up.v1",
      "ActionUrn": "urn:ugs:cloud-code:InitializeNewPlayer",
      "ActionType": "cloud-code"
    }
  ]
}
```

Cloud Code モジュールを作成した場合は、以下の設定で `triggers-config.tr` ファイルを更新します。

```json
{
  "$schema": "https://ugs-config-schemas.unity3d.com/v1/triggers.schema.json",
  "Configs": [
    {
      "Name": "initialize-new-player",
      "EventType": "com.unity.services.player-auth.signed-up.v1",
      "ActionUrn": "urn:ugs:cloud-code:ModuleSample/InitializeNewPlayer",
      "ActionType": "cloud-code"
    }
  ]
}
```

UGS CLI ツールを使用して設定をデプロイします。

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

以下のようなレスポンスが返されます。

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

これで、プレイヤーがサインアップしたときに Cloud Code スクリプトまたはモジュールを実行するトリガーが設定されました。

> **Note:**
>
> **ノート:** 同じイベントについて異なる Cloud Code スクリプトまたはモジュールを実行する複数のトリガーを定義できます。このユースケースを拡張し、他のプレイヤーデータを初期化するためのトリガーをさらに追加できます。

## 結果の検証##validate-the-result

結果を検証するには、[Authentication サービス](https://services.docs.unity.com/player-auth/v1/#tag/player-authentication/operation/signup) を使用して新しいプレイヤーをサインアップします。これは、プレイヤーとして認証された任意の Unity Gaming Services のサービスを呼び出すことで行うことができます。

例えば、プレイヤー認証フローをトリガーするには、[Unity Dashboard](https://cloud.unity.com)


**Frame:**
![](/api/media?file=/cloud-code/media/images/cloud-code-generate-button.png)

の Cloud Code スクリプトページを通じて新しいプレイヤー ID を生成します。

`signed-up` イベントを発生させるようにトリガーが設定されている場合、新しいプレイヤーがサインアップするたびに、それらの値が Cloud Save で初期化されます。

1. [Unity Dashboard](https://cloud.unity.com) に移動します。
2. **Products** (製品) > **Player Management** (プレイヤー管理) を選択します。
3. リストからプレイヤーの 1 人を選択します。
4. **Cloud Save** > **Data** (データ) タブに移動します。
5. `HEALTH` および `STAMINA` キーが初期値の `100` とともに表示されます。
