Skip to content

Instantly share code, notes, and snippets.

@UCh
Created July 7, 2016 09:42
Show Gist options
  • Save UCh/529b5e67fc1bd58a064d0f59d3481918 to your computer and use it in GitHub Desktop.
Save UCh/529b5e67fc1bd58a064d0f59d3481918 to your computer and use it in GitHub Desktop.
Unity FPS counter for UI text component with minimal memory allocation
using System.Text;
using UnityEngine;
using UnityEngine.UI;
public class FPSCounter : MonoBehaviour {
private static readonly string FPS = " FPS ";
private static readonly int STRING_SIZE = FPS.Length + 2;
private Text textField;
public float updateInterval = 0.5F;
private float accum = 0;
private int frames = 0;
private float timeleft;
private StringBuilder stringBuilder = new StringBuilder(STRING_SIZE);
void Awake() {
textField = GetComponent<Text>();
timeleft = updateInterval;
}
void Update() {
timeleft -= Time.deltaTime;
accum += Time.timeScale / Time.deltaTime;
++frames;
if ( timeleft <= 0.0 )
{
stringBuilder.Remove(0, stringBuilder.Length);
int fps = (int)accum / frames;
stringBuilder.Append(fps);
stringBuilder.Append(FPS);
textField.text = stringBuilder.ToString();
timeleft = updateInterval;
accum = 0.0F;
frames = 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment