今天我们来实现显示网络延迟的功能,有点类似王者荣耀里的延迟
往往延迟超过200时,玩家就会知晓当前网络状况差,影响游戏体验
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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
using UnityEngine; namespace Utils { public class PingUtil : MonoBehaviour { public string ip = string.Empty; Ping ping; string label; GUIStyle guiStyle; void Start() { ip = "121.42.114.17"; // 这里我用的是我网站的ip(www.u3d8.com) 需要替换成自己的服务器ip SendPing(); guiStyle = new GUIStyle(); guiStyle.normal.background = null; guiStyle.fontSize = 40; } bool isNetWorkLose = false; void OnGUI() { if (Application.internetReachability == NetworkReachability.NotReachable) { label = "460"; SetColor(460); isNetWorkLose = true; } else if (isNetWorkLose || (null != ping && ping.isDone)) { isNetWorkLose = false; label = ping.time.ToString(); SetColor(ping.time); ping.DestroyPing(); ping = null; Invoke("SendPing", 1);//每秒Ping一次 } GUI.Label(new Rect(10, 50, 200, 50), "ping:" + label + "ms", guiStyle); } void SendPing() { ping = new Ping(ip); } /// <summary> /// 仿王者荣耀延迟过高,颜色变化 /// </summary> /// <param name="pingValue"></param> void SetColor(int pingValue) { if (pingValue < 100) { guiStyle.normal.textColor = new Color(0, 1, 0); } else if (pingValue < 200) { guiStyle.normal.textColor = new Color(1, 1, 0); } else { guiStyle.normal.textColor = new Color(1, 0, 0); } } } } |
- 本文固定链接: http://www.u3d8.com/?p=1192
- 转载请注明: 网虫虫 在 u3d8.com 发表过