Last active
February 20, 2020 02:49
-
-
Save wonkee-kim/bf18f1e7d69a6afd95555fd867d4229f to your computer and use it in GitHub Desktop.
Unity C# - FPS Display
This file contains 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 UnityEngine; | |
using UnityEngine.UI; | |
public class FPSDisplay : MonoBehaviour { | |
[SerializeField] private Canvas _canvas; | |
[SerializeField] private Text _text; | |
[SerializeField] private float _refreshTime = 0.5f; | |
private float _timer = 0; | |
private int _frameCount = 0; | |
[SerializeField] private bool _isEnabled = false; | |
private bool _isEnabled_cached = false; | |
private void Awake() { | |
_isEnabled_cached = _isEnabled; | |
if(_text == null) { | |
_text = this.GetComponentInChildren<Text>(); | |
} | |
if(_canvas != null) { | |
_canvas.enabled = _isEnabled; | |
} | |
} | |
private void Update() { | |
#if UNITY_EDITOR | |
if(Input.GetKeyDown(KeyCode.F)) { | |
_isEnabled = !_isEnabled; | |
} | |
#endif | |
//if(OVRInput.GetDown(OVRInput.Button.Four)) { | |
// _isEnabled = !_isEnabled; | |
//} | |
if(_isEnabled != _isEnabled_cached) { | |
_isEnabled_cached = _isEnabled; | |
if(_canvas != null) { | |
_canvas.enabled = _isEnabled; | |
} | |
} | |
if(_isEnabled) { | |
Measure2(); | |
} | |
} | |
private void Measure1() { | |
if(_text == null) return; | |
_timer += Time.unscaledDeltaTime; | |
_frameCount++; | |
if(_timer > _refreshTime) { | |
float DTavg = _timer / _frameCount; | |
float millis = Mathf.Round(DTavg * 1000); | |
float fps = Mathf.Round(1f / DTavg); | |
_text.text = millis + " ms\n" + fps + " fps"; | |
_timer = 0; | |
_frameCount = 0; | |
} | |
} | |
private void Measure2() { | |
if(_text == null) return; | |
if(_timer < _refreshTime) { | |
_timer += Time.unscaledDeltaTime; | |
_frameCount++; | |
} else { | |
float millis = Mathf.Round(1000f * _timer / _frameCount); | |
float fps = Mathf.Round((float)_frameCount / _timer); | |
_text.text = millis + " ms\n" + fps + " fps"; | |
_timer = 0; | |
_frameCount = 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment