Show an FPS Counter in Unity: Accurate Frame Time Display

Illustration: a glowing digital FPS readout with a frame-time graph

You cannot fix performance you cannot see. A small on-screen readout of frames per second and frame time is the quickest way to spot a slow scene, compare quality settings on a phone or confirm that a fix worked. This guide builds a Unity FPS counter that shows smoothed FPS, frame time in milliseconds and min/max values, updates a TextMeshPro label without creating garbage, and only appears in development builds. It also explains why the number in the Editor lies and where the Profiler fits in.

The Simplest Counter and Why It Flickers

FPS is one divided by the time the last frame took:

float fps = 1f / Time.unscaledDeltaTime;

Use unscaledDeltaTime, not deltaTime. The scaled version is multiplied by Time.timeScale, so a paused game (timeScale 0) would divide by zero and a slow-motion game would show nonsense. The unscaled version is real time.

If you print this every frame, the text is unreadable. The value jumps around because individual frames vary, and a label that changes 60 times per second is a blur. The fix is to average over a short window and refresh the text a few times a second.

A Smoothed Counter

Count frames and add up time, then update once per interval. This gives the true average over that interval, which is more honest than averaging single-frame FPS values.

using UnityEngine;

public class FpsCounter : MonoBehaviour
{
    [SerializeField] float updateInterval = 0.5f;

    float timeAccumulated;
    int frames;

    public float Fps { get; private set; }
    public float FrameMs { get; private set; }

    void Update()
    {
        timeAccumulated += Time.unscaledDeltaTime;
        frames++;

        if (timeAccumulated >= updateInterval)
        {
            Fps = frames / timeAccumulated;
            FrameMs = 1000f * timeAccumulated / frames;
            timeAccumulated = 0f;
            frames = 0;
        }
    }
}

Averaging frames over the window and dividing total time by frame count means one slow frame in the middle of fast ones is reflected proportionally. An interval of 0.5 seconds is a good balance. Shorter reacts faster but flickers. Unity also offers Time.smoothDeltaTime, a built-in smoothed value, but it is scaled by timeScale, so the custom counter above is a better fit for tools that must work while paused.

Garbage-Free TextMeshPro Updates

The obvious way to show the value creates garbage every update:

label.text = "FPS: " + fps.ToString("0");   // allocates strings

Each call allocates new strings that the garbage collector must clean up later, which can itself cause small hitches, and an FPS counter that causes hitches is a bad joke. TextMeshPro has an allocation-free alternative, SetText, which takes a format string and numeric arguments:

using TMPro;
using UnityEngine;

[RequireComponent(typeof(FpsCounter))]
public class FpsDisplay : MonoBehaviour
{
    [SerializeField] TMP_Text label;
    [SerializeField] float refreshInterval = 0.5f;

    FpsCounter counter;
    float nextRefresh;

    void Awake() => counter = GetComponent<FpsCounter>();

    void Update()
    {
        if (Time.unscaledTime < nextRefresh) return;
        nextRefresh = Time.unscaledTime + refreshInterval;

        // {0:0} = no decimals, {1:1} = one decimal place
        label.SetText("{0:0} FPS\n{1:1} ms", counter.Fps, counter.FrameMs);
    }
}

The format placeholders in SetText use the number after the colon as the count of decimal places. {0:0} prints whole numbers, {1:1} prints one decimal. Because TMP formats the numbers internally into its own buffer, no strings are created. The garbage collection guide explains why avoiding per-frame allocations matters, and the TextMeshPro tutorial covers setting up the label. Put the label on a Canvas anchored to a corner, with a small font and a semi-transparent background so it is readable on any scene.

Frame Time and Min/Max Tracking

FPS is a nonlinear number. Going from 60 to 30 FPS costs 16.7 ms extra, while 120 to 90 costs only 2.8 ms, even though both drops look similar. Frame time in milliseconds is what you budget against. At 60 FPS you have 16.7 ms per frame, at 30 FPS 33.3 ms, at 120 FPS 8.3 ms. The performance budgets guide shows how to split that time between systems.

An average can hide stutters. Track the best and worst frame time in each window as well:

float worstMs;
float bestMs = float.MaxValue;

void Update()
{
    float dt = Time.unscaledDeltaTime;
    timeAccumulated += dt;
    frames++;

    float ms = dt * 1000f;
    if (ms > worstMs) worstMs = ms;
    if (ms < bestMs) bestMs = ms;

    if (timeAccumulated >= updateInterval)
    {
        Fps = frames / timeAccumulated;
        FrameMs = 1000f * timeAccumulated / frames;
        WorstMs = worstMs;
        BestMs = bestMs;

        timeAccumulated = 0f;
        frames = 0;
        worstMs = 0f;
        bestMs = float.MaxValue;
    }
}

Expose WorstMs and BestMs as properties and show them in the label:

label.SetText("{0:0} FPS  {1:1} ms\nbest {2:1}  worst {3:1}",
              counter.Fps, counter.FrameMs, counter.BestMs, counter.WorstMs);

SetText accepts several numeric arguments. If the worst number is much higher than the average, the game has spikes, and those usually come from garbage collection, loading, instantiating objects or a heavy script. That is the cue to open the Profiler.

Showing It Only in Development Builds

Players do not need a debug overlay. Hide it in release builds with Debug.isDebugBuild, which is true in the Editor and in builds made with Development Build checked in the Build Profiles or Build Settings window.

void Awake()
{
    if (!Debug.isDebugBuild)
    {
        gameObject.SetActive(false);
        return;
    }
    counter = GetComponent<FpsCounter>();
}

Or add a hotkey to toggle it, which is handy for testers:

using UnityEngine.InputSystem;

void Update()
{
    if (Keyboard.current != null && Keyboard.current.f3Key.wasPressedThisFrame)
        label.enabled = !label.enabled;
}

If you want a counter in release builds for a settings option, make that a player choice, off by default.

Why the Number Lies

  • The Editor is slow. The Game view, Inspector, Scene view and gizmos all cost frame time. An Editor FPS number is not what players will see. Measure on a real build, on the target device.
  • VSync caps the number. With VSync on, FPS is locked to the display refresh rate (often 60) even if the game could run faster. Turn VSync off (QualitySettings.vSyncCount = 0) when measuring raw speed.
  • Target frame rate caps it. Application.targetFrameRate limits FPS. On mobile it often defaults to 30 or 60. A counter stuck at exactly 30 usually means a cap, not a slow game.
  • The first seconds are noisy. Loading, shader compilation and warm-up spike the early frames. Let the scene run a bit before reading it.
  • Phones throttle. After a few minutes of load, a phone’s chip slows down to control heat, and FPS falls. See the mobile overheating guide for how to test and fix that.

When to Use the Profiler Instead

An FPS counter tells you that the game is slow. It cannot tell you why. When the worst-frame number jumps or the average is under budget, open the Profiler (Window > Analysis > Profiler) and look at the CPU Usage module for the expensive frames. Check whether the time is in scripts, rendering or physics, and watch the GC Alloc column for allocations. The Profiler beginner’s guide walks through reading it. For targets on phones and tablets, the mobile optimization guide lists the usual culprits.

The best workflow is to use both: the on-screen counter on a development build for quick checks while playing, and the Profiler (connected to the device) when something looks wrong.

💻 Test on real hardware

A slow dev machine makes every profiling session painful. See our guide to the best budget laptops for Unity development.

Troubleshooting

FPS counter shows Infinity or NaN

Division by zero, usually from using Time.deltaTime while timeScale is 0, or dividing by a zero-length window on the first frame. Use unscaledDeltaTime and only divide after the interval has passed.

Counter is stuck at exactly 60 or 30

VSync or Application.targetFrameRate is capping it. Turn VSync off in Project Settings > Quality or set QualitySettings.vSyncCount = 0 to measure uncapped speed.

The text flickers and is unreadable

The label updates every frame. Refresh about twice a second and use an averaged value.

The counter itself causes GC Alloc

You are building strings with + or ToString each update. Use TMP_Text.SetText with number arguments, and refresh less often.

Counter does not show in a build

If you disabled it with Debug.isDebugBuild, the build was not a Development Build. Also check that the Canvas is set up for the build’s resolution and the label is not behind other UI.

FPS is high in the Editor but low on the device

The Editor machine is faster than the target. Profile on the device with a development build and connect the Profiler to it.

FAQ

What FPS should I aim for?

60 FPS is the common target for PC and console, and 30 or 60 for mobile. Competitive or VR games aim higher. What matters most is a steady frame time without spikes.

Is Time.deltaTime or unscaledDeltaTime better for an FPS counter?

Use unscaledDeltaTime. It ignores Time.timeScale, so the counter keeps working in pause menus and slow motion.

Does the counter itself hurt performance?

Barely, if you use SetText and update the label a couple of times a second. Updating a TMP label every frame costs more because the text mesh is rebuilt.

Should I use OnGUI instead of TextMeshPro?

OnGUI is quick to write but allocates and is slower. A TextMeshPro label on a Canvas is the better choice for anything that stays in your project.

How do I show a 1% low FPS?

Store frame times in a fixed-size array over the last few seconds, sort a copy and read the slowest one percent. Do the sort only when refreshing the label, not every frame, and use a preallocated array to avoid garbage.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *