コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】FPS を計測するスクリプト

スクリプト

using UnityEngine;
public sealed class FPSCounter
{
private readonly int m_updateRate;
private int m_frameCount;
private float m_deltaTime;
private float m_fps;
public float FPS => m_fps;
public FPSCounter( int updateRate = 4 )
{
m_updateRate = updateRate;
}
public void Update()
{
m_deltaTime += Time.unscaledDeltaTime;
m_frameCount++;
if ( !( m_deltaTime > 1f / m_updateRate ) ) return;
m_fps = m_frameCount / m_deltaTime;
m_deltaTime = 0;
m_frameCount = 0;
}
}
view raw FPSCounter.cs hosted with ❤ by GitHub

使用例

using UnityEngine;

public class Example : MonoBehaviour
{
    private readonly FPSCounter m_fpsCounter = new FPSCounter();

    private void Awake()
    {
        Application.targetFrameRate = 60;
    }

    private void Update()
    {
        m_fpsCounter.Update();
    }

    private void OnGUI()
    {
        GUILayout.Label( $"{m_fpsCounter.FPS:#} fps" );
    }
}

補足

上記の FPSCounter は「Graphy」のソースコードを参考にさせていただきました

関連記事