# 시작하기

> 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 프로젝트 ID를 확인할 수 있습니다.

1. Unity 에디터에서 **Edit** > **Project Settings** > **Services**를 선택합니다.

2. 프로젝트를 연결합니다.

   * 프로젝트에 Unity 프로젝트 ID가 없는 경우 다음 단계를 진행합니다.

     1. **Create a Unity Project ID** > **Organizations**를 선택한 다음 드롭다운 메뉴에서 조직을 선택합니다.
     2. **Create project ID**를 선택합니다.

   * Unity 프로젝트 ID가 있는 경우 다음 단계를 진행합니다.

     1. **Use an existing Unity project ID**를 선택합니다.
     2. 드롭다운 메뉴에서 조직과 프로젝트를 선택합니다.
     3. **Link project ID**를 선택합니다.

Unity 프로젝트 ID가 표시되고 이제 Unity 서비스에 프로젝트가 연결됩니다. `UnityEditor.CloudProjectSettings.projectId`를 사용하여 Unity 에디터 스크립트에서 프로젝트 ID에 액세스할 수도 있습니다.

#### SDK 설치##sdkinstallation

다음 단계를 따라 Unity 에디터용 최신 Cloud Code 패키지를 설치합니다.

1. Unity 에디터에서 **Window** > **Package Manager**를 엽니다.
2. Package Manager에서 **Unity Registry** 목록 뷰를 선택합니다.
3. `com.unity.services.cloudcode`를 검색하거나 목록에서 Cloud Code 패키지를 찾습니다.
4. 패키지를 선택하고 **Install**을 클릭합니다.

자세한 내용은 [패키지 관리자](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 페이지에서 하나 이상의 클라우드 스크립트를 저작(authoring)해야 합니다. 그런 다음 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 서비스 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를 다른 서비스와 연동하기 위한 사용 사례 샘플을 참고합니다. |
