Course contentsShow
← Unity Game Development
Lesson 805 of 82812. Multiplayer and DeploymentFree lesson

Integrating Netcode for GameObjects with Relay Transports

Configure the Unity Transport package to route NGO network traffic through Relay servers for seamless peer-to-peer connectivity.

In this lesson, you will learn how to configure the UnityTransport component to bridge your Netcode for GameObjects (NGO) application with Unity Relay, enabling players to connect across different networks without manual port forwarding.

The Role of Relay Transport

By default, UnityTransport acts as a direct socket-based communicator. However, most players reside behind firewalls or NATs that block incoming traffic, making a direct peer-to-peer connection impossible. The Unity Relay service acts as a middleman, assigning your game session a unique allocation ID and a relay server address. By routing your NGO traffic through this relay, the server and client exchange data via the relay’s infrastructure rather than directly, ensuring seamless connectivity.

Integrating the Transport

To enable this, you must swap the default transport configuration in the NetworkManager component. Instead of using the default "Relay" settings via manual string manipulation, you attach the UnityTransport component to the same GameObject as your NetworkManager. When a host creates a relay allocation, you receive a RelayServerData object. You inject this data into the transport so that it knows exactly where to send packets.

Here is how you programmatically assign the relay connection to the transport:

using Unity.Netcode;
using Unity.Netcode.Transports.UTP;
using Unity.Networking.Transport.Relay;

// After receiving allocation data from the Relay Service
var relayServerData = new RelayServerData(allocation, "dtls");

// Get the existing transport component
UnityTransport transport = NetworkManager.Singleton.GetComponent<UnityTransport>();

// Set the relay server data to route NGO traffic through the Relay
transport.SetRelayServerData(relayServerData);

Once SetRelayServerData is called, any subsequent call to NetworkManager.Singleton.StartHost() or StartClient() will automatically route all NGO traffic through the Relay server. This replaces the default IP and port logic, effectively letting your NetworkManager focus on high-level game logic while the transport handles the complex task of traversing the network.

Key Takeaway: By injecting RelayServerData into your UnityTransport component, you instruct NGO to bypass direct socket connections in favor of the Relay service, ensuring reliable connectivity for all players regardless of their network configuration.