Unity如何将当前的帧率显示在UI界面
实现原理
获取时间间隔:首先,我们需要计算每一帧之间的时间间隔。在Unity中,可以使用Time.deltaTime来获取上一帧到当前帧的时间间隔。
计算帧率:通过时间间隔,我们可以计算出帧率。帧率是指每秒钟渲染的帧数,可以通过将1除以时间间隔来得到。
显示帧率:最后,我们将计算得到的帧率显示在屏幕上。在Unity中,可以使用GUI系统来实现,在屏幕上绘制文本来显示帧率。
using System.Collections;
using UnityEngine;
namespace ToolsModule
{
public class FPSDisplay : MonoBehaviour
{
private float _deltaTime = 0.0f;
private float _fps = 0.0f;
private float updateInterval = 0.5f; // 更新间隔(毫秒)
private GUIStyle _style;
private string _text;
private float _msec;
private void Start()
{
_style = new GUIStyle();
_style.alignment = TextAnchor.UpperLeft;
_style.fontSize = (int)(Screen.height * 0.02f);
_style.normal.textColor = Color.black;
StartCoroutine(UpdateFPS());
}
private IEnumerator UpdateFPS()
{
while (true)
{
yield return new WaitForSeconds(updateInterval); // 将毫秒转换为秒
_msec = _deltaTime * 1000.0f;
_fps = 1.0f / _deltaTime;
_text = string.Format("{0:0.0} ms ({1:0.} fps)", _msec, _fps);
}
}
private void Update()
{
_deltaTime += (Time.unscaledDeltaTime - _deltaTime) * 0.1f;
}
private void OnGUI()
{
int w = Screen.width, h = Screen.height;
Rect rect = new Rect(0, 0, w, h *0.02f);
GUI.Label(rect, _text, _style);
}
}
}
这部分代码只在编辑器模式下生效
#if UNITY_EDITOR
new GameObject("FPSDisplay").AddComponent<FPSDisplay>();
#endif