服务质量 (QoS)

注意:如果您当前搭配 WebSockets/WebGL 使用 Relay,则 QoS 不起作用。

Relay 的服务质量 (QoS) 特性支持在不选择目标地区的情况下,通过以主机玩家身份启动 NetworkDriver 来基于服务质量数据自动选择地区。

注意:并非所有 Unity 编辑器版本都支持 QoS。如果计划使用 QoS SDK,请确保您使用的是以下版本之一:

  • 2022.2.0a10+
  • 2022.1.0f1+
  • 2021.3.2f1+
  • 2020.3.34f1+

创建分配请求时不指定地区,会触发分配服务使用服务质量数据选择最合适的可用地区,选择的依据是每个地区和主机玩家之间的连接质量。Relay 将延迟和丢包都考虑在内。请查看以下示例代码。

// Launch this method as a coroutine
private IEnumerator StartRelayServer()
{

  // Request an allocation to the Relay service without a target region
  var relayMaxPlayers = 5;
  var allocationTask = RelayService.Instance.CreateAllocationAsync(relayMaxPlayers);

  while(!allocationTask.IsCompleted)
  {
      yield return null;
  }

  if (allocationTask.IsFaulted)
  {
      Debug.LogError("Create allocation request failed");
      yield break;
  }

  var allocation = allocationTask.Result;

  // Request the join code to the Relay service
  var joinCodeTask = RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);

  while(!joinCodeTask.IsCompleted)
  {
      yield return null;
  }

  if (joinCodeTask.IsFaulted)
  {
      Debug.LogError("Create join code request failed");
      yield break;
  }

  // Get the Join Code, you can then share it with the clients so they can join
  JoinCode = joinCodeTask.Result;

  // Format the server data, based on desired connectionType
  var relayServerData = HostRelayData(allocation, "dtls");

  // Create the network parameters using the Relay server data
  var relayNetworkParameter = new RelayNetworkParameter{ ServerData = relayServerData };

  // Bind and listen to the Relay server
  yield return ServerBindAndListen(relayNetworkParameter);
}

下图展示了 Relay 如何根据主机玩家客户端和可用地区之间的 QoS 数据选择地区。如果无法定位 QoS 服务器或收集测量数据,Relay 会使用客户端的位置来选择最近的地区。如果客户端的位置无法确定,则会选择默认地区,即美国中部。