Unity打印FPS

规定时间内的帧数除以时间。

using UnityEngine;

/// <summary>
/// 打印FPS
/// </summary>
public class FPS : MonoBehaviour
{
    
    
    float _updateInterval = 1f;//设定更新帧率的时间间隔为1秒  
    float _accum = .0f;//累积时间  
    int _frames = 0;//在_updateInterval时间内运行了多少帧  
    float _timeLeft;
    string fpsFormat;

    void Start()
    {
    
    
        _timeLeft = _updateInterval;
        Application.targetFrameRate = 300;
    }
    
    void OnGUI()
    {
    
    
        GUI.Label(new Rect(100, 100, 200, 200), fpsFormat);
    }

    void Update()
    {
    
    
        _timeLeft -= Time.deltaTime;
        //Time.timeScale可以控制Update 和LateUpdate 的执行速度,  
        //Time.deltaTime是以秒计算,完成最后一帧的时间  
        //相除即可得到相应的一帧所用的时间  
        _accum += Time.timeScale * Time.deltaTime;
        ++_frames;//帧数  

        
        if (_timeLeft <= 0)
        {
    
    
            float fps =  _frames / _accum;
            //Debug.Log(_accum + "__" + _frames);  
            fpsFormat = System.String.Format("{0:F2}FPS ; TargetFrameRate {1:F2}", fps, Application.targetFrameRate);//保留两位小数  
            Debug.LogError(fpsFormat);

            _timeLeft = _updateInterval;
            _accum = .0f;
            _frames = 0;
        }
    }
}

最高帧率的限制一般上来说,是由 Application.targetFrameRate确定。所以有时最高帧率可能会因为场景不同而不同。

参考Unity目标帧率文档 Application.targetFrameRate给出的设置最大帧率的代码

using UnityEngine;

public class Example
{
    
    
    void Start()
    {
    
    
        // Make the game run as fast as possible
        Application.targetFrameRate = 300;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43149049/article/details/128232364
FPS
今日推荐