FPS.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using UnityEngine;
  2. /// <summary>
  3. /// 打印FPS
  4. /// </summary>
  5. public class FPS : MonoBehaviour
  6. {
  7. float _updateInterval = 1f;//设定更新帧率的时间间隔为1秒
  8. float _accum = .0f;//累积时间
  9. int _frames = 0;//在_updateInterval时间内运行了多少帧
  10. float _timeLeft;
  11. string fpsFormat;
  12. void Start()
  13. {
  14. _timeLeft = _updateInterval;
  15. }
  16. bool FPS_True = false;
  17. void OnGUI()
  18. {
  19. if (FPS_True)
  20. {
  21. GUI.Label(new Rect(100, 100, 200, 200), fpsFormat);
  22. }
  23. }
  24. void Update()
  25. {
  26. if (Input.GetKeyDown(KeyCode.X))
  27. {
  28. FPS_True = !FPS_True;
  29. }
  30. _timeLeft -= Time.deltaTime;
  31. //Time.timeScale可以控制Update 和LateUpdate 的执行速度,
  32. //Time.deltaTime是以秒计算,完成最后一帧的时间
  33. //相除即可得到相应的一帧所用的时间
  34. _accum += Time.timeScale / Time.deltaTime;
  35. ++_frames;//帧数
  36. if (_timeLeft <= 0)
  37. {
  38. float fps = _accum / _frames;
  39. //Debug.Log(_accum + "__" + _frames);
  40. fpsFormat = System.String.Format("{0:F2}FPS", fps);//保留两位小数
  41. //Debug.LogError(fpsFormat);
  42. _timeLeft = _updateInterval;
  43. _accum = .0f;
  44. _frames = 0;
  45. }
  46. }
  47. }