Unity获取网络延迟

在游戏中,通常需要显示网络状态。类似王者荣耀右上角的网络XX MS。通常使用Ping来检测网络状态。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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);
}

}
如果您觉得我的文章对您有所帮助,不妨小额捐助一下,您的鼓励是我长期坚持的动力。