Skip to content

Instantly share code, notes, and snippets.

@michael-sacco
Created December 10, 2021 07:23
Show Gist options
  • Select an option

  • Save michael-sacco/188c4c0a3538160463904eca2a3f8ac9 to your computer and use it in GitHub Desktop.

Select an option

Save michael-sacco/188c4c0a3538160463904eca2a3f8ac9 to your computer and use it in GitHub Desktop.
Simple Frame Time Calculator for Unity. Works with TextMeshPro. Sends to DebugLog if TMPro is unavailable.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace OccaSoftware
{
public class FPSCounter : MonoBehaviour
{
float deltaTime;
float realtimePrevious;
float trailingAvg;
float delayDuration = 3f;
float timeSinceActive = 0f;
bool startCheckingFrameData = false;
TMPro.TextMeshProUGUI text;
private void Start()
{
if (TryGetComponent(out TMPro.TextMeshProUGUI temp))
{
text = temp;
text.SetText("");
}
}
void Update()
{
if (!startCheckingFrameData)
{
DoWait();
}
else
{
DoCheckFrameData();
}
}
void DoWait()
{
timeSinceActive += Time.deltaTime;
if (timeSinceActive > delayDuration)
{
startCheckingFrameData = true;
trailingAvg = Time.deltaTime / 0.001f;
realtimePrevious = Time.realtimeSinceStartup;
}
}
void DoCheckFrameData()
{
float delta = Time.realtimeSinceStartup - realtimePrevious;
realtimePrevious = Time.realtimeSinceStartup;
delta /= 0.001f;
trailingAvg = Mathf.Lerp(trailingAvg, delta, 0.005f);
string trailingAvgStr = string.Format("{0:N2}", System.Math.Round(trailingAvg, 2));
string deltaStr = string.Format("{0:N2}", System.Math.Round(delta, 2));
string trailingFpsStr = string.Format("{0:N0}", 1000.0f / trailingAvg);
string textToPrint = "trailing avg (ms) " + trailingAvgStr + "\ncurrent frame (ms) " + deltaStr + "\nFPS " + trailingFpsStr;
if (text == null)
Debug.Log(textToPrint);
else
text.SetText(textToPrint);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment