Skip to content

Instantly share code, notes, and snippets.

@mstevenson
Last active November 8, 2024 02:25
Show Gist options
  • Save mstevenson/5103365 to your computer and use it in GitHub Desktop.
Save mstevenson/5103365 to your computer and use it in GitHub Desktop.
An accurate FPS counter for Unity. Works in builds.
using UnityEngine;
using System.Collections;
public class Fps : MonoBehaviour
{
private float count;
private IEnumerator Start()
{
GUI.depth = 2;
while (true)
{
count = 1f / Time.unscaledDeltaTime;
yield return new WaitForSeconds(0.1f);
}
}
private void OnGUI()
{
GUI.Label(new Rect(5, 40, 100, 25), "FPS: " + Mathf.Round(count));
}
}
@Ahmad1441
Copy link

To get smooth FPS (Weighted average over time):

using UnityEngine;
using System.Collections;

public class Fps : MonoBehaviour
{
    private float currentFps;
    private float smoothedFps;
    private float smoothingFactor = 0.1f; // Adjust this to control how much weight is given to recent FPS

    private IEnumerator Start()
    {
        GUI.depth = 2;
        while (true)
        {
            currentFps = 1f / Time.unscaledDeltaTime;

            // Apply exponential smoothing to calculate the weighted average
            smoothedFps = (smoothingFactor * currentFps) + (1f - smoothingFactor) * smoothedFps;

            yield return new WaitForSeconds(0.1f);
        }
    }

    private void OnGUI()
    {
        // Display the smoothed FPS
        GUI.Label(new Rect(5, 40, 100, 25), "FPS: " + Mathf.Round(smoothedFps));
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment