기술 자료

지원

Relay

Relay

NGO(Netcode for GameObjects)와 함께 Relay 사용

Integrate Relay with Netcode for GameObjects using the unified Multiplayer Services SDK.
읽는 시간 2분최근 업데이트: 한 달 전

Relay는
GameObject
MonoBehavior
워크플로에 네트워킹 기능을 제공하는 Unity 패키지인 NGO(Netcode for GameObjects)와 함께 원활하게 작동합니다. NGO 프레임워크는 UTP(Unity Transport 패키지)를 포함한 여러 로우레벨 전송을 지원합니다.

Relay SDK 설정

Relay를 NGO와 함께 사용하려면 Unity 프로젝트를 Unity용으로 설정해야 합니다. Relay 시작하기를 확인하십시오. Relay 서비스를 활성화하고 Unity 에디터를 통해 Unity 프로젝트 ID를 연결하면 요구 사항을 임포트하고,
NetworkManager
를 설정하고, Unity 서비스로 플레이어를 인증하고, Relay SDK를 사용할 수 있습니다.
Relay SDK를 설정한 다음에는 호스트 플레이어연결 플레이어로 Relay 게임 세션에 참여하는 데 필요한 작업을 수행하도록 게임 클라이언트를 설정합니다.

요구 사항 임포트

Relay 서비스를 사용하려면 다른 네임스페이스와 함께 Relay SDK와 UTP를 임포트해야 합니다. 패키지 및 SDK 다운로드 센터에서 생성한 코드 스니핏을 사용하면 됩니다.
  1. Unity Dashboard에 로그인합니다.
  2. Packages and SDK Download Center로 이동합니다.
  3. 다음 패키지를 선택합니다.
    • Relay
    • Netcode for GameObjects
  4. Generate Code Snippet을 선택하고 지침을 따릅니다.
다음 코드 샘플은 요구 사항 임포트 예시를 보여 줍니다.
using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using UnityEngine;using Unity.Services.Core;using Unity.Services.Authentication;using Unity.Services.Relay;using Unity.Services.Relay.Http;using Unity.Services.Relay.Models;using Unity.Netcode;using Unity.Netcode.Transports.UTP;using Unity.Networking.Transport;using Unity.Networking.Transport.Relay;using NetworkEvent = Unity.Networking.Transport.NetworkEvent;

NetworkManager 설정

Unity Dashboard에서 패키지를 설치한 다음 Unity 에디터에서 프로젝트에 Relay 및 NGO용
NetworkManager
를 설정합니다.
  1. 씬에 새 게임 오브젝트를 추가합니다.
  2. NetworkManager MonoBehavior를 추가합니다.
  3. MonoBehavior 프로퍼티에서 UnityTransport 전송을 선택합니다. UnityTransport를 선택하면 컴포넌트 목록 하단에 'Unity Transport (script)'라는
    MonoBehavior
    가 표시됩니다.
  4. 새 컴포넌트의 Protocol TypeRelay Unity Transport로 설정합니다.

변수 및 유틸리티 함수 설정

최대 연결 수, 참여 코드 등 몇 가지 변수를 초기화해야 합니다.
const int m_MaxConnections = 4;public string RelayJoinCode;

플레이어 인증

호스트 플레이어와 연결 플레이어 모두를 인증해야 합니다. 플레이어를 인증하는 가장 간단한 방법은 Authentication 서비스의
SignInAnonymouslyAsync()
메서드를 사용하는 것입니다. 익명 로그인 사용 방법플랫폼별 로그인 사용 방법을 참조하십시오.
더 자세한 내용은 Unity Authentication 소개Unity Authentication 사용 사례를 참조하십시오.
async void Example_AuthenticatingAPlayer(){ try { await UnityServices.InitializeAsync(); await AuthenticationService.Instance.SignInAnonymouslyAsync(); var playerID = AuthenticationService.Instance.PlayerId; } catch (Exception e) { Debug.Log(e); }}

호스트 플레이어

게임 클라이언트가 호스트 플레이어로 작동하는 경우, 게임 클라이언트는 할당을 생성하고, 참여 코드를 요청하며, 연결 유형을 설정하고,
NetworkDriver
의 싱글톤 인스턴스를 생성하여 Relay 서버에 바인드한 다음 참여 플레이어의 연결 요청을 수신할 수 있어야 합니다.

할당 생성 및 참여 코드 요청

다음 코드 스니핏은
AllocateRelayServerAndGetJoinCode
함수를 사용한 것으로, Relay SDK를 사용하여 할당을 생성하고, 참여 코드를 요청하고, 연결 유형을 DTLS로 설정하는 방법을 보여 줍니다.
public static async Task<RelayServerData> AllocateRelayServerAndGetJoinCode(int maxConnections, string region = null){ Allocation allocation; string createJoinCode; try { allocation = await RelayService.Instance.CreateAllocationAsync(maxConnections, region); } catch (Exception e) { Debug.LogError($"Relay create allocation request failed {e.Message}"); throw; } Debug.Log($"server: {allocation.ConnectionData[0]} {allocation.ConnectionData[1]}"); Debug.Log($"server: {allocation.AllocationId}"); try { createJoinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId); } catch { Debug.LogError("Relay create join code request failed"); throw; } return new RelayServerData(allocation, "dtls");}

전송 설정 및 NGO 시작

다음 코드 스니핏은
ConfigureTransportAndStartNgoAsHost
함수를 사용한 것으로, Relay SDK와 NGO SDK를 사용하여 전송을 설정하고 호스트 플레이어로 NGO를 시작하는 방법을 보여 줍니다.
IEnumerator Example_ConfigureTransportAndStartNgoAsHost(){ var serverRelayUtilityTask = AllocateRelayServerAndGetJoinCode(m_MaxConnections); while (!serverRelayUtilityTask.IsCompleted) { yield return null; } if (serverRelayUtilityTask.IsFaulted) { Debug.LogError("Exception thrown when attempting to start Relay Server. Server not started. Exception: " + serverRelayUtilityTask.Exception.Message); yield break; } var relayServerData = serverRelayUtilityTask.Result; // Display the joinCode to the user. NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(relayServerData); NetworkManager.Singleton.StartHost(); yield return null;}

참여 플레이어

게임 클라이언트가 참여 플레이어로 작동하는 경우, 게임 클라이언트는 할당에 참여하고, 연결 유형을 설정하며,
NetworkDriver
의 싱글톤 인스턴스를 생성하여 Relay 서버에 바인드한 다음 호스트 플레이어에게 연결 요청을 전송할 수 있어야 합니다.

할당 참여

다음 코드 스니핏은
JoinRelayServerFromJoinCode
함수를 사용한 것으로, Relay SDK를 사용하여 참여 코드로 할당에 참여하고, 연결 유형을 DTLS로 설정하는 방법을 보여 줍니다.
public static async Task<RelayServerData> JoinRelayServerFromJoinCode(string joinCode){ JoinAllocation allocation; try { allocation = await RelayService.Instance.JoinAllocationAsync(joinCode); } catch { Debug.LogError("Relay create join code request failed"); throw; } Debug.Log($"client: {allocation.ConnectionData[0]} {allocation.ConnectionData[1]}"); Debug.Log($"host: {allocation.HostConnectionData[0]} {allocation.HostConnectionData[1]}"); Debug.Log($"client: {allocation.AllocationId}"); return new RelayServerData(allocation, "dtls");}

전송 설정 및 참여 플레이어로 NGO 시작

다음 샘플 코드는 전송을 설정하고 참여 플레이어로 NGO(Netcode for GameObjects)를 시작하는 방법을 보여 줍니다.
IEnumerator Example_ConfigureTransportAndStartNgoAsConnectingPlayer(){ // Populate RelayJoinCode beforehand through the UI var clientRelayUtilityTask = JoinRelayServerFromJoinCode(RelayJoinCode); while (!clientRelayUtilityTask.IsCompleted) { yield return null; } if (clientRelayUtilityTask.IsFaulted) { Debug.LogError("Exception thrown when attempting to connect to Relay Server. Exception: " + clientRelayUtilityTask.Exception.Message); yield break; } var relayServerData = clientRelayUtilityTask.Result; NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(relayServerData); NetworkManager.Singleton.StartClient(); yield return null;}