HUDFPS.cs 1.7 KB

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