在游戏中,通常需要显示网络状态。类似王者荣耀右上角的网络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);
}
}
网友评论