Unity FPS 计数器
在视频游戏中,每秒帧数(简称fps)是一个表示计算机在一秒钟内渲染的帧数的值。
每秒帧数 是一个很好的性能指标,可以在优化 过程中使用,或者只是为了获得有关游戏运行速度/流畅程度的反馈。
在本教程中,我将展示如何在 Unity 中向游戏添加一个简单的 fps 计数器。
脚步
要在 game 中显示 fps,我们需要创建一个脚本来计算帧数并将其显示在屏幕上。
- 创建 一个新脚本,将其命名为 "SC_FPSCounter" 并将以下代码粘贴到其中:
SC_FPSCounter.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SC_FPSCounter : MonoBehaviour
{
/* Assign this script to any object in the Scene to display frames per second */
public float updateInterval = 0.5f; //How often should the number update
float accum = 0.0f;
int frames = 0;
float timeleft;
float fps;
GUIStyle textStyle = new GUIStyle();
// Use this for initialization
void Start()
{
timeleft = updateInterval;
textStyle.fontStyle = FontStyle.Bold;
textStyle.normal.textColor = Color.white;
}
// Update is called once per frame
void Update()
{
timeleft -= Time.deltaTime;
accum += Time.timeScale / Time.deltaTime;
++frames;
// Interval ended - update GUI text and start new interval
if (timeleft <= 0.0)
{
// display two fractional digits (f2 format)
fps = (accum / frames);
timeleft = updateInterval;
accum = 0.0f;
frames = 0;
}
}
void OnGUI()
{
//Display the fps and round to 2 decimals
GUI.Label(new Rect(5, 5, 100, 25), fps.ToString("F2") + "FPS", textStyle);
}
}
- 将 SC_FPSCounter 脚本附加到场景中的任何对象并按“播放”:
FPS 现在应该显示在左上角。