Unity FPS 计算

FPS 是一段时间内的平均值。平均 FPS = 帧数 / 一段时长。帧数可以用每次进入 Update 时加一的变量来统计。一段时长就是进入 Update 时 Time.deltaTime 的累加因为是平均值

public class FPSDisplay : MonoBehaviour {

    public float showTime = 1f;
    public Text tvFpsInfo;

    private int m_count = 0;
    private float m_deltaTime = 0f;

    private void Update () {
        m_count++;
        m_deltaTime += Time.deltaTime;
        if (m_deltaTime >= showTime) {
            float fps = m_count / m_deltaTime;
            float ms = m_deltaTime * 1000 / m_count;
            Debug.Log($"{fps} FPS ({ms}ms)");
            m_count = 0;
            m_deltaTime = 0f;
        }
    }
}

优化写法

using UnityEngine;
using System.Collections;

public class FPSDisplay : MonoBehaviour{

	private float m_time = 0.0f;

	void Update(){
		m_time += (Time.unscaledDeltaTime - m_time) * 0.1f;
		
		float ms = m_time * 1000.0f;
		float fps = 1.0f / m_time;
		
		Debug.Log($"{fps} FPS ({ms}ms)");
	}

}
原文地址:https://www.cnblogs.com/kingBook/p/15097736.html