The host is working but my client is not able to find the join code.
using System;
using System.Threading.Tasks;
using UnityEngine;
using Unity.Services.Core;
using Unity.Services.Authentication;
using Unity.Services.Relay;
using Unity.Services.Relay.Models;
using Unity.Netcode;
using Unity.Netcode.Transports.UTP;
using Unity.Networking.Transport.Relay;
using TMPro;
public class TestRelay : MonoBehaviour
{
[SerializeField] private TextMeshProUGUI joinCodeText;
[SerializeField] private TMP_InputField joinCodeInputField;
public async void StartRelay()
{
try
{
string joinCode = await StartHostWithRelay();
if (!string.IsNullOrEmpty(joinCode))
{
joinCodeText.text = joinCode;
Debug.Log($"Relay started. Join code: {joinCode}");
}
else
{
Debug.LogError("Failed to start relay. Join code is null or empty.");
}
}
catch (Exception e)
{
Debug.LogError($"Failed to start relay: {e.Message}");
}
}
public async void JoinRelay()
{
try
{
string joinCode = joinCodeInputField.text;
Debug.Log($"Attempting to join relay with code: {joinCode}");
if (string.IsNullOrEmpty(joinCode))
{
Debug.LogError("Join code is empty. Please enter a valid join code.");
return;
}
bool result = await StartClientWithRelay(joinCode);
if (result)
{
Debug.Log("Client connected successfully.");
}
else
{
Debug.LogError("Client failed to connect.");
}
}
catch (Exception e)
{
Debug.LogError($"Failed to join relay: {e.Message}");
}
}
public async Task<string> StartHostWithRelay(int maxConnections = 5)
{
await UnityServices.InitializeAsync();
if (!AuthenticationService.Instance.IsSignedIn)
{
await AuthenticationService.Instance.SignInAnonymouslyAsync();
}
Allocation allocation = await RelayService.Instance.CreateAllocationAsync(maxConnections);
//NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(new RelayServerData(allocation, "dtls"));
//for webgl (dont forget to check in unity tranpsort (networkmanager) websockets
var unityTransport = NetworkManager.Singleton.GetComponent<UnityTransport>();
unityTransport.SetRelayServerData(new RelayServerData(allocation, "wss"));
unityTransport.UseWebSockets = true;
var joinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
return NetworkManager.Singleton.StartHost() ? joinCode : null;
}
public async Task<bool> StartClientWithRelay(string joinCode)
{
await UnityServices.InitializeAsync();
if (!AuthenticationService.Instance.IsSignedIn)
{
await AuthenticationService.Instance.SignInAnonymouslyAsync();
}
var joinAllocation = await RelayService.Instance.JoinAllocationAsync(joinCode: joinCode);
//NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(new RelayServerData(joinAllocation, "dtls"));
//for webgl
var unityTransport = NetworkManager.Singleton.GetComponent<UnityTransport>();
unityTransport.SetRelayServerData(new RelayServerData(joinAllocation, "wss"));
unityTransport.UseWebSockets = true;
return !string.IsNullOrEmpty(joinCode) && NetworkManager.Singleton.StartClient();
}
}