# DTO

> Define data transfer objects to transfer data between client and server.

모듈에서 DTO(데이터 전송 오브젝트)를 정의할 수 있습니다. DTO는 클라이언트와 서버 간에 데이터를 전송하는 데 사용됩니다.

예를 들어 DTO는 모듈 데이터를 JSON으로 직렬화한 후 클라이언트 측에서 동일한 구조로 역직렬화하려는 경우에 유용할 수 있습니다.

> **Important:**
>
> **중요**: Unity 에디터에서 바인딩을 생성하여 유형 안전성을 유지하는 클라이언트 코드를 사용해 모듈 엔드포인트를 호출할 수 있습니다. 대부분의 사용 사례에서는 Unity 프로젝트에 DTO를 수동으로 만들 필요가 없습니다. 자세한 내용은 [에디터 바인딩 사용](../run-modules/unity-runtime#use-editor-bindings)을 참고하십시오.

## 필수 조건##prerequisites

DTO를 시작하려면 먼저 [Cloud Code 모듈](../../getting-started)을 생성해야 합니다.

## DTO 관리##manage-dtos

모듈 엔드포인트 함수의 데이터 유형을 캡처하는 DTO를 정의할 수 있습니다.

### DTO 프로젝트 생성 및 구성##create-and-configure-your-dto-project

시작하려면 DTO를 저장할 C# 프로젝트를 만들고 메인 프로젝트에서 해당 프로젝트에 대한 레퍼런스를 추가합니다. [프로젝트에서 레퍼런스를 관리](https://learn.microsoft.com/en-us/visualstudio/ide/managing-references-in-a-project?view=vs-2022)하는 방법에 관한 Microsoft 기술 자료를 참고하십시오.

모듈에 관한 자세한 내용은 [모듈 구조](../module-structure)를 참고하십시오.

그다음 Unity 에디터에서 지원되는 런타임 .NET 버전(`netstandard`)을 사용하도록 DTO C# 프로젝트를 구성해야 합니다.

`<project_name>.csproj` 파일을 열고 `TargetFramework`를 변경합니다. Unity 2021.2.0을 사용하는 경우에는 `netstandard.2.1`입니다.

자세한 내용은 Unity 매뉴얼의 [지원되는 .NET 버전](https://docs.unity3d.com/2021.2/Documentation/Manual/dotnetProfileSupport.html)을 참고하십시오.

ImplicitUsings를 비활성화해야 합니다. 아래의 C# 프로젝트 구성 예시를 참고하십시오.

```xml
<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <TargetFramework>netstandard2.1</TargetFramework>
        <ImplicitUsings>disable</ImplicitUsings>
        <RootNamespace>DTOSample</RootNamespace>
    </PropertyGroup>

</Project>
```

### 모듈에 DTO 추가##add-the-dtos-to-your-module

모듈에 DTO를 추가하려면 프로젝트에서 새 클래스를 정의하여 DTO를 저장해야 합니다. 이는 다음 예시와 유사할 수 있습니다.

```csharp
namespace DTOSample
{
    public class DiceRollDto
    {
        public DiceRollDto(int roll, int sides)
        {
            Roll = roll;
            Sides = sides;
        }

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

### 모듈 로직에 DTO 사용##use-dtos-in-your-module-logic

모듈 함수가 포함된 메인 프로젝트에서 게임 로직을 정의하고, 정의된 DTO를 함수 반환 유형으로 사용합니다.

간단한 모듈 엔드포인트의 예시는 다음과 같습니다.

```csharp
using DTOSample;
using Unity.Services.CloudCode.Core;

namespace Sample;

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

        return new DiceRollDTO(roll, diceSides);
    }

}
```

> **Note:**
>
> **참고**: 입력의 함수 파라미터로 DTO를 사용할 수도 있습니다.

### DLL 추출##extract-the-dlls

응답 유형과 일치하는 DTO를 Unity 프로젝트에서 사용하려면 모듈 C# 프로젝트에서 DLL을 추출해야 합니다.

이 단계에서는 나중에 모듈 함수를 호출할 수 있도록 [모듈을 배포](../../getting-started#deploy-the-module)해야 합니다.

매뉴얼 패키지의 경우 어셈블리를 생성하는 방법에 관한 자세한 내용은 [코드 패키징](../package-code)을 참고하십시오.

모듈을 배포할 때 어셈블리를 생성하면 기본적으로 모듈 프로젝트의 `bin/Debug/Release/net6.0/linux-x64/publish` 폴더에서 DLL을 찾을 수 있습니다.

어셈블리는 다음 예시와 유사합니다.

```text
├─ Main.csproj
    └─ bin
        └─ Debug
            └─ Release
                └─ net6.0
                    └─ linux-x64
                        └─ publish
                            └─ Main.dll
                            └─ Main.pdb
                            └─ DTOs.dll
                            └─ DTOs.pdb
                            ...
```

`DTOs.dll` 파일을 복사합니다.

### Unity 프로젝트로 DLL 임포트##import-the-dlls-to-unity-project

게임에 외부 DLL을 사용하려면 Unity 프로젝트 내부의 `Assets` 디렉토리에 DLL을 배치하면 됩니다.

이후에 Unity 에디터에서 프로젝트를 동기화하면 에디터는 필요한 레퍼런스를 DLL에 추가합니다.

자세한 내용은 Unity 매뉴얼의 [관리되는 플러그인](https://docs.unity3d.com/Manual/UsingDLL.html)을 참고하십시오.

### Unity MonoBehaviour 스크립트에서 DTO 재사용##reuse-the-dtos-in-a-unity-monobehaviour-script

Cloud Code SDK를 호출하고 동일한 DTO를 사용하여 응답을 역직렬화할 수 있습니다.

```csharp
using DTOSample;
using UnityEngine;
using Unity.Services.Authentication;
using Unity.Services.CloudCode;
using Unity.Services.Core;

public class Test : MonoBehaviour
{
    // Call this method to roll the dice (use a button)
    public async void Awake()
    {
        await UnityServices.InitializeAsync();
        // Sign in anonymously to the Authentication service
        if (!AuthenticationService.Instance.IsSignedIn) await AuthenticationService.Instance.SignInAnonymouslyAsync();

        // Call out to the Roll Dice script in Cloud Code
        var response = await CloudCodeService.Instance.CallModuleEndpointAsync<DiceRollDto>("Main", "RollDice", new Dictionary<string, object>()
        {
            {"diceSides", 6}
        });

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

다음의 성공적인 응답 예시를 레퍼런스로 사용합니다.

```text
"You rolled 5 / 6"
```

자세한 내용은 [Unity Runtime에서 모듈 실행](../run-modules/unity-runtime)을 참고하십시오.
