As far as I know, we can only set the Protocol Type of Unity Transport in Inspector. Is there a way to set it with code?
When you call SetConnectionData or SetRelayServerData, the protocol automatically gets updated to the appropriate value (respectively, “Unity Transport” or “Relay Unity Transport”).
In the Inspector, I set the Protocol Type of Unity Transport to Relay Unity Transport, then I tried the following code:
private async Task<Allocation> AllocateRelay()
{
try
{
Allocation allocation = await RelayService.Instance.CreateAllocationAsync(4);
return allocation;
}
catch (RelayServiceException e)
{
Debug.Log(e);
return default;
}
}
private async void StartHostForSingleplayerMode()
{
Allocation allocation = await AllocateRelay();
NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(new RelayServerData(allocation, "dtls"));
NetworkManager.Singleton.StartHost();
}
private void Start()
{
StartHostForSingleplayerMode();
}
If I used “dtls” as the connectionType, the Protocol Type will still be set to Relay Unity Transport in the Inspector.
But if I used “udp” as the connectionType, the “NetworkManager.Singleton.StartHost()” line will cause Null Reference Exception error.
Is the “udp” connectionType supposed to set the Protocol Type to Unity Transport or should I use another method?
Can you post the stack trace for that null reference exception?
After re-trying “udp” as the connectionType, the “NetworkManager.Singleton.StartHost()” line doesn’t cause Null Reference Exception error anymore. Maybe I forgot to recompile the scripts or there was a connection problem with the relay server.
But the Protocol Type is still Relay Unity Transport in Inspector, despite using “udp” as the connectionType. Should I use another connectionType to set the Protocol Type to Unity Transport at runtime?
No, if you use Relay it is expected for the protocol type to be “Relay Unity Transport”. Doesn’t matter if you use “udp” or “dtls” as the connection type. The “Unity Transport” connection type is for direct IP connections (i.e. not using Relay).
So, if we select Relay Unity Transport as the Protocol Type in the Inspector, is it possible to change it to Unity Transport at runtime using code? If yes, could you please show the code example?
Yes, it’s possible. If you set the IP address and port to connect to with SetConnectionData, it will automatically switch the protocol type to “Unity Transport”. Here’s an example:
NetworkManager.Singleton.GetComponent<UnityTransport>().SetConnectionData("127.0.0.1", 7777);
Thanks, it works
Thanks, saved me.