DTO

모듈에서 DTO(데이터 전송 오브젝트)를 정의할 수 있습니다. DTO는 클라이언트와 서버 간에 데이터를 전송하는 데 사용됩니다. DTO는 모듈 데이터를 JSON으로 직렬화한 후 클라이언트 측에서 동일한 구조로 역직렬화하려는 경우에 유용할 수 있습니다.

필수 조건

DTO를 시작하려면 먼저 Cloud Code 모듈을 생성해야 합니다.

DTO 관리

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

DTO 프로젝트 생성 및 구성

시작하려면 DTO를 저장할 C# 프로젝트를 생성하고 메인 프로젝트에서 해당 프로젝트에 대한 레퍼런스를 추가합니다. 프로젝트의 레퍼런스 관리(Microsoft)(영문)를 참고하십시오.

자세한 내용은 모듈 구조를 참고하시기 바랍니다.

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

<project_name>.csproj 파일을 열고 TargetFramework를 변경합니다. Unity 2021.2.0을 사용하는 경우 .NET 버전은 netstandard.2.1입니다. 자세한 내용은 지원되는 .NET 버전(Unity 매뉴얼)을 참고하십시오. ImplicitUsings를 비활성화해야 합니다. 아래의 C# 프로젝트 구성 예시를 참고하십시오.

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

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

</Project>

모듈에 DTO 추가

프로젝트에서 새 클래스를 정의하여 DTO를 저장합니다. 구현 예시는 다음과 같습니다.

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 사용

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

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

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);
    }

}

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

DLL 추출

응답 유형과 일치하는 DTO를 Unity 프로젝트에서 사용하려면 모듈 C# 프로젝트에서 DLL을 추출해야 합니다. 이 단계에서는 나중에 모듈 함수를 호출할 수 있도록 모듈을 배포해야 합니다.

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

어셈블리의 예시는 다음과 같습니다.

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

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

어셈블리 생성 방법에 대한 자세한 내용은 코드 패키징을 참고하십시오.

Unity 프로젝트로 DLL 임포트

게임에 외부 DLL을 사용하려면 Unity 프로젝트 내부의 Assets 디렉토리에 배치하면 됩니다. 이후에 Unity 에디터에서 프로젝트를 동기화하면 필요한 레퍼런스가 DLL에 추가됩니다.

자세한 내용은 관리되는 플러그인(Unity 매뉴얼)을 참고하십시오.

Unity MonoBehaviour 스크립트에서 DTO 재사용

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

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 into 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}");
    }
}

성공적인 응답의 예시는 다음과 같습니다.

"You rolled 5 / 6"

자세한 내용은 Unity Runtime에서 모듈 실행을 참고하십시오.