核心脚本:
using UnityEngine;
/// <summary>
/// 使用方式:Get时调用:实例化一个obj,添加FPSShow组件,Init
/// </summary>
public class FPSShow : MonoBehaviour
{
Rect rect = new Rect(new Vector2(50, 20), new Vector2(800,150));
GUIStyle uIStyle=new GUIStyle();
public float _UpdateInterval = 0.5f;//每隔0.5s刷新一次
private float _LastInterval;
private int _Frames = 0;
private float _FPS;
public bool showFPS = true;
bool hasInit = false;
public void Init()
{
if (hasInit) return;
hasInit = true;
_LastInterval = Time.realtimeSinceStartup;
_Frames = 0;
uIStyle.fontSize = 80;
}
void Update()
{
_Frames++;
if (Time.realtimeSinceStartup > _LastInterval + _UpdateInterval)
{
_FPS = _Frames / (Time.realtimeSinceStartup - _LastInterval);
_Frames = 0;
_LastInterval = Time.realtimeSinceStartup;
}
}
void OnGUI()
{
if (showFPS)
{
GUI.Label(rect, _FPS.ToString(), uIStyle);
}
}
}
测试用例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestCtrl : MonoBehaviour
{
public bool showFPS;
FPSShow fPS;
public FPSShow FPS
{
get
{
if (fPS == null)
{
var _obj = new GameObject();
_obj.name = "FPS";
fPS=_obj.AddComponent<FPSShow>();
fPS.Init();
}
return fPS;
}
set
{
fPS = value;
}
}
private void Update()
{
FPS.showFPS = showFPS;
}
}
返回目录:https://blog.csdn.net/yzy1987523/article/details/107739933