Unity帧率的计算和显示

要显示帧率,得先知道帧率是什么:帧率是Unity单位时间内刷新的次数。

所以,帧率=帧数/单位时间

那么,代码怎么写就很简单了:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Text))]
public class Test : MonoBehaviour {
 
    const float fpsMeasurePeriod = 0.5f;//固定时间为0.5s
    private int m_FpsAccumulator = 0;
    private float m_FpsNextPeriod = 0;
    private int m_CurrentFps;
    const string display = "{0} FPS";//输出格式
    private Text mText;
    private void Start()
    {
        //Time.realtimeSinceStartup  游戏开始的真实时间
        m_FpsNextPeriod = Time.realtimeSinceStartup + fpsMeasurePeriod;//下一次刷新时间
        mText=this.GetComponent();
    }
    private void Update()
    {
        // measure average frames per second
        //计算每秒的平均帧数
        m_FpsAccumulator++;
        if (Time.realtimeSinceStartup > m_FpsNextPeriod)
        {
            m_CurrentFps = (int)(m_FpsAccumulator / fpsMeasurePeriod);
            m_FpsAccumulator = 0;
            m_FpsNextPeriod += fpsMeasurePeriod;
            mText.text = string.Format(display, m_CurrentFps);
        }
    }
 
}

转载请注明出处。

你可能感兴趣的:(Unity性能优化,unity,c#)