Unityネットワーク遅延の取得
1418 ワード
ゲームでは、通常、ネットワークの状態を表示する必要があります.王者栄耀右上のネットワークXX MSに似ています.通常Pingを用いてネットワーク状態を検出する.
using System.Linq;
using System.Text;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;;
public class GUIMainNetWorkInfo : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField]
UILabel labelBattery;
StringBuilder sb = new StringBuilder();
public string ip = string.Empty;
Ping ping;
Color bestColor = new Color(0.5f,0.63f,0.39f);
Color normalColor = new Color(1,1,0);
bool isNetWorkLose = false;
void Start()
{
ip = ClientMainContext.ServerAddress.Ip;
SendPing();
}
private void Update() {
if (Application.internetReachability == NetworkReachability.NotReachable)
{
sb.Remove(0, sb.Length);
labelBattery.text = "-MS";
isNetWorkLose = true;
}
else if (isNetWorkLose || (null != ping && ping.isDone))
{
isNetWorkLose = false;
sb.Remove(0, sb.Length);
sb.Append(ping.time);
sb.Append("MS");
labelBattery.text = sb.ToString();
ping.DestroyPing();
ping = null;
Invoke("SendPing", 1);// Ping
}
}
void SendPing()
{
ping = new Ping(ip);
}
}