FPSCounter.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. namespace NRKernal
  2. {
  3. using UnityEngine;
  4. /// <summary> The FPS counter. </summary>
  5. public class FPSCounter : MonoBehaviour
  6. {
  7. /// <summary> The frame range. </summary>
  8. public int frameRange = 60;
  9. /// <summary> Gets or sets the average FPS. </summary>
  10. /// <value> The average FPS. </value>
  11. public int AverageFPS { get; private set; }
  12. /// <summary> Gets or sets the highest FPS. </summary>
  13. /// <value> The highest FPS. </value>
  14. public int HighestFPS { get; private set; }
  15. /// <summary> Gets or sets the lowest FPS. </summary>
  16. /// <value> The lowest FPS. </value>
  17. public int LowestFPS { get; private set; }
  18. /// <summary> Buffer for FPS data. </summary>
  19. int[] fpsBuffer;
  20. /// <summary> Zero-based index of the FPS buffer. </summary>
  21. int fpsBufferIndex;
  22. /// <summary> Updates this object. </summary>
  23. void Update()
  24. {
  25. if (fpsBuffer == null || fpsBuffer.Length != frameRange)
  26. {
  27. InitializeBuffer();
  28. }
  29. UpdateBuffer();
  30. CalculateFPS();
  31. }
  32. /// <summary> Initializes the buffer. </summary>
  33. void InitializeBuffer()
  34. {
  35. if (frameRange <= 0)
  36. {
  37. frameRange = 1;
  38. }
  39. fpsBuffer = new int[frameRange];
  40. fpsBufferIndex = 0;
  41. }
  42. /// <summary> Updates the buffer. </summary>
  43. void UpdateBuffer()
  44. {
  45. fpsBuffer[fpsBufferIndex++] = (int)(1f / Time.unscaledDeltaTime);
  46. if (fpsBufferIndex >= frameRange)
  47. {
  48. fpsBufferIndex = 0;
  49. }
  50. }
  51. /// <summary> Calculates the FPS. </summary>
  52. void CalculateFPS()
  53. {
  54. int sum = 0;
  55. int highest = 0;
  56. int lowest = int.MaxValue;
  57. for (int i = 0; i < frameRange; i++)
  58. {
  59. int fps = fpsBuffer[i];
  60. sum += fps;
  61. if (fps > highest)
  62. {
  63. highest = fps;
  64. }
  65. if (fps < lowest)
  66. {
  67. lowest = fps;
  68. }
  69. }
  70. AverageFPS = (int)((float)sum / frameRange);
  71. HighestFPS = highest;
  72. LowestFPS = lowest;
  73. }
  74. }
  75. }