Skip to content

Instantly share code, notes, and snippets.

@sanukin39
Last active June 8, 2023 20:48
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sanukin39/63bdfcf6c57466abe6d44ac5a79c5ca9 to your computer and use it in GitHub Desktop.
Save sanukin39/63bdfcf6c57466abe6d44ac5a79c5ca9 to your computer and use it in GitHub Desktop.
Simple FPS conter for Unity
using UnityEngine;
/// <summary>
/// ~ Fps counter for unity ~
/// Brief : Calculate the FPS and display it on the screen
/// HowTo : Create empty object at initial scene and attach this script!!!
/// </summary>
public class UniFPSCounter : MonoBehaviour
{
// for ui.
private int screenLongSide;
private Rect boxRect;
private GUIStyle style = new GUIStyle();
// for fps calculation.
private int frameCount;
private float elapsedTime;
private double frameRate;
/// <summary>
/// Initialization
/// </summary>
private void Awake()
{
DontDestroyOnLoad(gameObject);
UpdateUISize();
}
/// <summary>
/// Monitor changes in resolution and calcurate FPS
/// </summary>
private void Update()
{
// FPS calculation
frameCount++;
elapsedTime += Time.deltaTime;
if (elapsedTime > 0.5f)
{
frameRate = System.Math.Round(frameCount / elapsedTime, 1, System.MidpointRounding.AwayFromZero);
frameCount = 0;
elapsedTime = 0;
// Update the UI size if the resolution has changed
if (screenLongSide != Mathf.Max(Screen.width, Screen.height))
{
UpdateUISize();
}
}
}
/// <summary>
/// Resize the UI according to the screen resolution
/// </summary>
private void UpdateUISize()
{
screenLongSide = Mathf.Max(Screen.width, Screen.height);
var rectLongSide = screenLongSide / 10;
boxRect = new Rect(1, 1, rectLongSide, rectLongSide / 3);
style.fontSize = (int)(screenLongSide / 36.8);
style.normal.textColor = Color.white;
}
/// <summary>
/// Display FPS
/// </summary>
private void OnGUI()
{
GUI.Box(boxRect, "");
GUI.Label(boxRect, " " + frameRate + "fps", style);
}
}
@Kabir404
Copy link

Kabir404 commented Jul 6, 2021

Thanks bud, It really helped :D

@Tetti
Copy link

Tetti commented Aug 22, 2021

Exactly, what I was looking for 🙂
Thanks!

@Saharsh1223
Copy link

@sanukin39 bruh in the editor stats i get 200 to 250 fps and the fps counter shows 100 to 150 fps

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