HUDFPS.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using UnityEngine;
  2. using System.Collections;
  3. public class HUDFPS : MonoBehaviour
  4. {
  5. private static HUDFPS instance;
  6. public static HUDFPS Instance { get { return instance; } }
  7. // Attach this to a GUIText to make a frames/second indicator.
  8. //
  9. // It calculates frames/second over each updateInterval,
  10. // so the display does not keep changing wildly.
  11. //
  12. // It is also fairly accurate at very low FPS counts (<10).
  13. // We do this not by simply counting frames per interval, but
  14. // by accumulating FPS for each frame. This way we end up with
  15. // correct overall FPS even if the interval renders something like
  16. // 5.5 frames.
  17. public float updateInterval = 0.5F;
  18. private float accum = 0; // FPS accumulated over the interval
  19. private int frames = 0; // Frames drawn over the interval
  20. private float timeleft; // Left time for current interval
  21. public float fps;
  22. void Start()
  23. {
  24. instance = this;
  25. if (!GetComponent<GUIText>())
  26. {
  27. AVDebug.Log("UtilityFramesPerSecond needs a GUIText component!");
  28. enabled = false;
  29. return;
  30. }
  31. timeleft = updateInterval;
  32. }
  33. void Update()
  34. {
  35. timeleft -= Time.deltaTime;
  36. accum += Time.timeScale / Time.deltaTime;
  37. ++frames;
  38. // Interval ended - update GUI text and start new interval
  39. if (timeleft <= 0.0)
  40. {
  41. // display two fractional digits (f2 format)
  42. fps = accum / frames;
  43. string format = System.String.Format("{0:F2} FPS", fps);
  44. GetComponent<GUIText>().text = format;
  45. if (fps < 30)
  46. {
  47. GetComponent<GUIText>().material.color = Color.yellow;
  48. }
  49. else
  50. if (fps < 10)
  51. {
  52. GetComponent<GUIText>().material.color = Color.red;
  53. }
  54. else
  55. {
  56. GetComponent<GUIText>().material.color = Color.green;
  57. }
  58. // DebugConsole.Log(format,level);
  59. timeleft = updateInterval;
  60. accum = 0.0F;
  61. frames = 0;
  62. }
  63. }
  64. }