读到雨松的《unity3d游戏开发第2版》第4章-4.2.5使用OnGUI显示FPS。觉得我的游戏中应该会经常用到,能用来检测到底哪里卡了,在这里就分享一下。
public class ShowFPS : MonoBehaviour
{
public float updateInterval = 0.5F;
private float accum = 0;
private int frames = 0;
private float timeleft;
private string stringFps;
void Start()
{
timeleft = updateInterval;
}
void Update()
{
timeleft -= Time.deltaTime;
accum += Time.timeScale / Time.deltaTime;
++frames;
if (timeleft <= 0.0) {
float fps = accum / frames;
string format = System.String.Format ("{0:F2} FPS", fps);
stringFps = format;
timeleft = updateInterval;
accum = 0.0F;
frames = 0;
}
}
void OnGUI()
{
GUIStyle guiStyle = GUIStyle.none;
guiStyle.fontSize = 30;
guiStyle.normal.textColor = Color.red;
guiStyle.alignment = TextAnchor.UpperLeft;
Rect rt = new Rect(40, 0, 100, 100);
GUI.Label(rt, stringFps, guiStyle);
}
}
找到卡的大概位置后,更准确一些还可以通过unity上部菜单的windows->Analysis->Profiler来分析性能的损耗点,最好打个pc包出来使用Profiler实际测试,因为编辑器的环境和真实运行环境有区别。打包前需要勾选上开发构建和自动连接探查器。 运行游戏然后在Profiler里面选择你正在运行的游戏选项,就能看到pc包的性能分析了。 windows->Analysis里面还有许多其他的性能分析的工具可用,看需要什么就用什么吧。


本文分享了如何在Unity中使用OnGUI显示FPS,监测游戏性能。通过代码示例介绍了实时FPS计算方法,并推荐使用Profiler进行更深入的性能分析。
458

被折叠的 条评论
为什么被折叠?



