ShowFPS.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System;
  5. using UnityEngine.UI;
  6. using UnityEngine.Events;
  7. using UnityEngine.EventSystems;
  8. namespace YLBattle
  9. {
  10. /// <summary>
  11. /// 显示 fps
  12. /// </summary>
  13. public class ShowFPS : MonoBehaviour
  14. {
  15. /// <summary>
  16. /// 更新间隔时间,单位:秒
  17. /// </summary>
  18. private float mInterval = 0.5f;
  19. /// <summary>
  20. /// 上一次计算 fps 的时间
  21. /// </summary>
  22. private float mLastTime = 0.0f;
  23. /// <summary>
  24. /// 帧数计数器
  25. /// </summary>
  26. private int mFrameNum = 0;
  27. /// <summary>
  28. /// 当前 fps
  29. /// </summary>
  30. private float mCurFPS = 0.0f;
  31. /// <summary>
  32. /// 当前ping/pong循环时间
  33. /// </summary>
  34. private int curTTs = 0;
  35. /// <summary>
  36. /// gui style
  37. /// </summary>
  38. private GUIStyle myStyle = new GUIStyle();
  39. private GUIStyle ttsStyle = new GUIStyle();
  40. /// <summary>
  41. /// 初始化
  42. /// </summary>
  43. private void Start()
  44. {
  45. mLastTime = Time.realtimeSinceStartup;
  46. mFrameNum = 0;
  47. myStyle.fontSize = 40;
  48. myStyle.normal.textColor = Color.yellow;
  49. ttsStyle.fontSize = 24;
  50. ttsStyle.normal.textColor = Color.green;
  51. }
  52. /// <summary>
  53. /// 更新
  54. /// </summary>
  55. private void Update()
  56. {
  57. mFrameNum++;
  58. float curTime = Time.realtimeSinceStartup;
  59. if ((mLastTime + mInterval) < curTime)
  60. {
  61. mCurFPS = (float)mFrameNum / (curTime - mLastTime);
  62. mFrameNum = 0;
  63. mLastTime = curTime;
  64. }
  65. curTTs = MapTcpProxy.Instance?.Peer.tts ?? -1;
  66. ttsStyle.normal.textColor = curTTs switch
  67. {
  68. > 100 => Color.red,
  69. > 50 => Color.yellow,
  70. _ => Color.green
  71. };
  72. }
  73. /// <summary>
  74. /// 显示 fps
  75. /// </summary>
  76. private void OnGUI()
  77. {
  78. GUI.Label(new Rect(0, 0, 50, 50), string.Format("FPS: {0:f2}", mCurFPS), myStyle);
  79. GUI.Label(new Rect(800, 0, 50, 50), $" rtts:{curTTs}ms", ttsStyle);
  80. }
  81. }
  82. }