美文网首页
Unity获取网络延迟

Unity获取网络延迟

作者: 吴少年 | 来源:发表于2019-05-23 20:31 被阅读0次

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

}

相关文章

网友评论

      本文标题:Unity获取网络延迟

      本文链接:https://www.haomeiwen.com/subject/gvjvzqtx.html