Files
Fishing2/Assets/Scripts/Demo/FPSCounter.cs
2025-08-29 09:11:08 +08:00

50 lines
1.2 KiB
C#

using UnityEngine;
public class FPSCounter : MonoBehaviour
{
private float updateInterval = 0.5f;
private float accum = 0f;
private int frames = 0;
private float timeleft;
private float fps = 0f;
private GUIStyle style;
private Color goodColor = Color.green; // >60 FPS
private Color warnColor = Color.yellow; // 30-60 FPS
private Color badColor = Color.red; // <30 FPS
void Start()
{
timeleft = updateInterval;
style = new GUIStyle();
style.alignment = TextAnchor.UpperRight;
style.fontSize = 20;
}
void Update()
{
timeleft -= Time.deltaTime;
accum += Time.timeScale / Time.deltaTime;
frames++;
if (timeleft <= 0f)
{
fps = accum / frames;
timeleft = updateInterval;
accum = 0f;
frames = 0;
}
}
void OnGUI()
{
// 根据FPS值设置颜色
if (fps > 60) style.normal.textColor = goodColor;
else if (fps > 30) style.normal.textColor = warnColor;
else style.normal.textColor = badColor;
GUI.Label(new Rect(Screen.width - 150, 10, 140, 30),
$"FPS: {fps:0.}", style);
}
}