# Unity Runtime에서 호출

> Invoke module endpoints from an authenticated game client in the Unity Editor.

Unity 에디터에서 인증된 게임 클라이언트로부터 모듈 엔드포인트를 호출하여 실행합니다.

> **Note:**
>
> **참고:** 지난 15분 내에 모듈에 어떤 트래픽도 수신되지 않으면 콜드 스타트 지연을 경험하게 될 수 있습니다. 모듈에 대한 후속 호출이 발생하면 이는 더 빠르게 처리됩니다.

## 필수 조건##prerequisites

Unity 에디터에서 Cloud Code를 사용하려면 먼저 Cloud Code SDK를 설치하고 [Unity Gaming Services 프로젝트](/cloud/projects.md)를 Unity 에디터에 연결해야 합니다.

## 프로젝트 연결##link-project

[Unity Gaming Services 프로젝트](/cloud/projects.md)를 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**을 클릭합니다.

> **Note:**
>
> [Unity - 매뉴얼: Package Manager 창](https://docs.unity3d.com/Manual/upm-ui.html)을 확인하여 Unity 패키지 관리자 인터페이스를 익혀 두십시오.

## SDK 설정##sdk-setup

다음 단계를 따라 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를 초기화합니다.

## 일반적인 워크플로##typical-workflow

Unity 에디터의 일반 MonoBehaviour C# 스크립트에서 Cloud Code SDK를 호출할 수 있습니다.

1. Unity 엔진 내에서 C# `MonoBehaviour` 스크립트를 생성합니다. [Unity - 매뉴얼: 스크립트 생성 및 사용](https://docs.unity3d.com/Manual/CreatingAndUsingScripts.html)을 참고하십시오.
2. `MonoBehaviour` 스크립트 내에서 [Unity Authentication](#authentication) 서비스를 구성합니다.
3. `MonoBehaviour` 스크립트 내에서 Cloud Code SDK에 호출을 추가합니다.
4. 게임 오브젝트에 `MonoBehaviour` 스크립트를 연결합니다. [에디터 스크립팅](https://docs.unity3d.com/Manual/ScriptingSection.html)을 참고하십시오.
5. **플레이** 버튼을 선택하고 프로젝트를 실행하여 Cloud Code가 작동하는지 확인합니다.

## Authentication##authentication

Cloud Code 서비스에 액세스하려면 플레이어에게 유효한 플레이어 ID와 액세스 토큰이 있어야 합니다. Cloud Code API를 사용하려면 먼저 Authentication SDK로 플레이어를 인증해야 합니다. C# Monobehaviour 스크립트 내에서 Authentication SDK를 초기화하여 인증할 수 있습니다. [인증 플레이어](../authentication#authenticate-players)를 참고하십시오.

Authentication SDK를 초기화하려면 C# Monobehaviour 스크립트에 다음을 추가합니다.

*C#*

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

익명 인증을 사용하여 시작하는 것이 좋습니다. 다음은 Authentication 패키지를 사용하여 익명 인증을 시작하고 Unity 에디터 내의 스크립트에서 플레이어 ID를 기록하는 방법을 보여 주는 예시입니다.

*C#*

```cs
using Unity.Services.Authentication;
using System.Threading.Tasks;
using Unity.Services.Core;
using UnityEngine;

public class AuthenticationExample : MonoBehaviour
{
    internal async Task Awake()
    {
        await UnityServices.InitializeAsync();
        await SignInAnonymously();
    }

    private async Task SignInAnonymously()
    {
        AuthenticationService.Instance.SignedIn += () =>
        {
            var playerId = AuthenticationService.Instance.PlayerId;

            Debug.Log("Signed in as: " + playerId);
        };
        AuthenticationService.Instance.SignInFailed += s =>
        {
            // Take some action here...
            Debug.Log(s);
        };

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

## Cloud Code 모듈 엔드포인트 호출##calling-a-cloud-code-module-endpoint

새로 생성한 스크립트에 인증을 포함하고 나면 Cloud Code 모듈 엔드포인트를 호출할 수 있습니다. 다음 네임스페이스를 포함해서 Cloud Code를 Unity 에디터 프로젝트와 연동합니다.

```cs
Using Unity.Services.CloudCode;
```

아래 샘플에서는 다음 코드를 사용해 `RollDice`라는 엔드포인트가 있는 `HelloWorld` 모듈을 배포했다고 가정합니다.

```csharp
using System;
using System.Threading.Tasks;
using Unity.Services.CloudCode.Core;

namespace HelloWorld;

public class HelloWorld
{
    public class Response
    {
        public Response(int roll, int sides)
        {
            Roll = roll;
            Sides = sides;
        }

        public int Roll { get; set; }
        public int Sides { get; set; }
    }

    [CloudCodeFunction("RollDice")]
    public async Task<Response> RollDice(int diceSides)
    {
        var random = new Random();
        var roll = random.Next(1, diceSides);

        return new Response(roll, diceSides);
    }
}
```

### 에디터 바인딩 사용##use-editor-bindings

Cloud Code 모듈에 대해 에디터 바인딩을 생성할 수 있으므로 Unity 에디터 인터페이스에서 에디터 바인딩을 사용할 수 있습니다. 자세히 알아보려면 [바인딩 생성](../write-modules/unity-editor#generate-bindings)을 참고하십시오.

다음 예시는 유형 안전성을 유지하여 Unity 에디터에서 Cloud Code 모듈을 호출하는 방법을 보여 줍니다. Unity 에디터에서 C# MonoBehaviour 스크립트 `RollDiceExample`을 만들고 다음 코드를 포함합니다.

*C#*

```cs
using Unity.Services.Authentication;
using Unity.Services.CloudCode;
using Unity.Services.CloudCode.GeneratedBindings;
using Unity.Services.Core;
using UnityEngine;

public class RollDiceExample : MonoBehaviour
{
    private async void Start()
    {
        // Initialize the Unity Services Core SDK
        await UnityServices.InitializeAsync();

        // Authenticate by logging into an anonymous account
        await AuthenticationService.Instance.SignInAnonymouslyAsync();

        try
        {
            // Call the function within the module and provide the parameters we defined in there
            var module = new HelloWorldBindings(CloudCodeService.Instance);
            var result = await module.RollDice(6);

            Debug.Log($"You've rolled {result.Roll}/{result.Sides}");
        }
        catch (CloudCodeException exception)
        {
            Debug.LogException(exception);
        }
    }
}
```

### `CallModuleEndpointAsync`##use-callmoduleendpointasync

`CloudCodeService.Instance`에서 찾을 수 있는 `CallModuleEndpointAsync` API 클라이언트를 사용할 수도 있습니다.

*C#*

```cs
        /// <summary>
        /// Calls a Cloud Code function.
        /// </summary>
        /// <param name="module">Cloud Code Module to call</param>
        /// <param name="function">Cloud Code function to call.</param>
        /// <param name="args">Arguments for the cloud code function. Will be serialized to JSON.</param>
        /// <typeparam name="TResult">Serialized from JSON returned by Cloud Code.</typeparam>
        /// <returns>Serialized output from the called function.</returns>
        /// <exception cref="CloudCodeException">Thrown if request is unsuccessful.</exception>
        /// <exception cref="CloudCodeRateLimitedException">Thrown if the service returned rate limited error.</exception>
        Task<TResult> CallModuleEndpointAsync<TResult>(string module, string function, Dictionary<string, object> args = null);
```

* `module` 파라미터는 모듈의 이름입니다.
* `function` 파라미터는 모듈 엔드포인트의 이름으로, `CloudCodeFunction` 속성으로 레이블을 지정한 것입니다.
* `args` 파라미터는 모듈 엔드포인트에 전달할 파라미터의 딕셔너리입니다.

Unity 에디터에서 C# MonoBehaviour 스크립트 `RollDiceExample`을 생성합니다. 다음은 Authentication과 Cloud Code 모두를 스크립트에 연동하는 방법에 대한 전체 예시입니다.

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

public class RollDiceExample : MonoBehaviour
{
    // ResultType structure is the serialized response from the RollDice script in Cloud Code
    private class ResultType
    {
        public int Roll;
        public int Sides;
    }

    // Call this method
    public async void CallMethod()
    {
        await UnityServices.InitializeAsync();
        // Sign in anonymously into the Authentication service
        if (!AuthenticationService.Instance.IsSignedIn) await AuthenticationService.Instance.SignInAnonymouslyAsync();

        // Call out to the RollDice endpoint in the HelloWorld module in Cloud Code
        var response = await CloudCodeService.Instance.CallModuleEndpointAsync<ResultType>("HelloWorld", "RollDice", new Dictionary<string, object>( ) { { "diceSides", 6 } });

        // Log the response of the module endpoint in console
        Debug.Log($"You rolled {response.Roll} / {response.Sides}");
    }
}
```

### 스크립트 실행##run-the-script

스크립트를 테스트하려면 Unity 에디터에서 게임 오브젝트에 스크립트를 연결한 후, **Play**를 선택합니다.

`Start()` 메서드에 다음 코드를 포함하여 `CallMethod()` 메서드를 호출할 수 있습니다.

```csharp
    public void Start()
    {
        CallMethod();
    }
```
