# 사용 사례 샘플: 새로 가입한 플레이어를 기본 구성 값으로 초기화

> 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 Configuration Viewer**를 선택합니다.
   * Admin 드롭다운에서 **Unity Environments Viewer**를 선택합니다.
3. **Save**를 선택합니다.
4. **Add Key**를 선택합니다.
5. base64 인코딩을 사용하여 **Key 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. 다음과 같이 프로젝트 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)의 Cloud Code 스크립트 페이지를 통해 신규 플레이어 ID를 생성하여 플레이어 인증 플로를 트리거할 수 있습니다.


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

`signed-up` 이벤트 발생 시 트리거가 발동하도록 구성된 경우 신규 플레이어가 가입할 때마다 Cloud Save에서 해당 플레이어의 값이 초기화됩니다.

1. [Unity Dashboard](https://cloud.unity.com)로 이동합니다.
2. **Products** > **Player Management**를 선택합니다.
3. 목록에서 플레이어 중 한 명을 선택합니다.
4. **Cloud Save** > **Data** 탭으로 이동합니다.
5. 기본값이 `100`인 `HEALTH`와 `STAMINA` 키를 확인할 수 있습니다.
