Last active
March 9, 2020 21:49
-
-
Save ogxd/62cf5023991f784744e9d81de1f2a0f0 to your computer and use it in GitHub Desktop.
A real framerate counter for Unity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
using UnityEngine; | |
[ExecuteInEditMode] | |
[RequireComponent(typeof(Camera))] | |
public class RealFramerate : MonoBehaviour { | |
public int framerate { get { return _framerate; } } | |
private int _framerate; | |
public bool maxPower = true; | |
private bool _maxPower = true; | |
private Queue<float> _deltas = new Queue<float>(); | |
private void Awake() { | |
Application.targetFrameRate = -1; | |
QualitySettings.vSyncCount = 0; | |
} | |
// Update is called once per frame | |
void Update () { | |
if (_maxPower != maxPower) { | |
_maxPower = maxPower; | |
Application.targetFrameRate = _maxPower? -1 : 60; | |
QualitySettings.vSyncCount = _maxPower? 0 : 1; | |
} | |
_deltas.Enqueue(Time.deltaTime); | |
_framerate = (int)Mathf.Round(1f / _deltas.Sum(o => o) * _deltas.Count); | |
int dampFrames = Mathf.Clamp(_framerate, 1, 250); | |
while (_deltas.Count > dampFrames) | |
_deltas.Dequeue(); | |
} | |
private void OnGUI() { | |
GUI.Label(new Rect(0, 0, Screen.width, Screen.height), _framerate + " FPS"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment