NGO(Netcode for GameObjects)와 함께 Relay 사용
Integrate Relay with Netcode for GameObjects using the unified Multiplayer Services SDK.
읽는 시간 2분최근 업데이트: 한 달 전
Relay는
GameObjectMonoBehaviorRelay SDK 설정
Relay를 NGO와 함께 사용하려면 Unity 프로젝트를 Unity용으로 설정해야 합니다. Relay 시작하기를 확인하십시오. Relay 서비스를 활성화하고 Unity 에디터를 통해 Unity 프로젝트 ID를 연결하면 요구 사항을 임포트하고,NetworkManager요구 사항 임포트
Relay 서비스를 사용하려면 다른 네임스페이스와 함께 Relay SDK와 UTP를 임포트해야 합니다. 패키지 및 SDK 다운로드 센터에서 생성한 코드 스니핏을 사용하면 됩니다.- Unity Dashboard에 로그인합니다.
- Packages and SDK Download Center로 이동합니다.
-
다음 패키지를 선택합니다.
- Relay
- Netcode for GameObjects
- 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- 씬에 새 게임 오브젝트를 추가합니다.
- NetworkManager MonoBehavior를 추가합니다.
- MonoBehavior 프로퍼티에서 UnityTransport 전송을 선택합니다. UnityTransport를 선택하면 컴포넌트 목록 하단에 'Unity Transport (script)'라는 가 표시됩니다.
MonoBehavior - 새 컴포넌트의 Protocol Type을 Relay Unity Transport로 설정합니다.
변수 및 유틸리티 함수 설정
최대 연결 수, 참여 코드 등 몇 가지 변수를 초기화해야 합니다.const int m_MaxConnections = 4;public string RelayJoinCode;
플레이어 인증
호스트 플레이어와 연결 플레이어 모두를 인증해야 합니다. 플레이어를 인증하는 가장 간단한 방법은 Authentication 서비스의SignInAnonymouslyAsync()async void Example_AuthenticatingAPlayer(){ try { await UnityServices.InitializeAsync(); await AuthenticationService.Instance.SignInAnonymouslyAsync(); var playerID = AuthenticationService.Instance.PlayerId; } catch (Exception e) { Debug.Log(e); }}
호스트 플레이어
게임 클라이언트가 호스트 플레이어로 작동하는 경우, 게임 클라이언트는 할당을 생성하고, 참여 코드를 요청하며, 연결 유형을 설정하고,NetworkDriver할당 생성 및 참여 코드 요청
다음 코드 스니핏은AllocateRelayServerAndGetJoinCodepublic 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 시작
다음 코드 스니핏은ConfigureTransportAndStartNgoAsHostIEnumerator 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할당 참여
다음 코드 스니핏은JoinRelayServerFromJoinCodepublic 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;}