網上有很多計算FPS的方法,一般計算沒有達到百分之百準確的幀率,只有更接近實際幀率的計算方式。
下面是本人測試多種方法之後覺得比較接近實際幀率的計算方式。
public class FPS : MonoBehaviour
{
[SerializeField]
private Text showFPSText;
private float fpsByDeltatime = 1.5f;
private float passedTime = 0.0f;
private int frameCount = 0;
private float realtimeFPS = 0.0f;
void Start()
{
SetFPS();
}
void Update()
{
GetFPS();
}
private void SetFPS()
{
//如果QualitySettings.vSyncCount屬性設置,這個值將被忽略。
//設置應用平臺目標幀率爲 60
Application.targetFrameRate = 60;
}
private void GetFPS()
{
if (showFPSText == null) return;
//第一種方式獲取FPS
//float fps = 1.0f / Time.smoothDeltaTime;
//showFPSText.text = "FPS: " + fps.ToString();
//第二種方式
frameCount++;
passedTime += Time.deltaTime;
if(passedTime >= fpsByDeltatime)
{
realtimeFPS = frameCount / passedTime;
showFPSText.text = "FPS: " + realtimeFPS.ToString("f1");
passedTime = 0.0f;
frameCount = 0;
}
}
}