1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【コピペで簡単】Unityで画面にFPSを表示したい

Last updated at Posted at 2023-03-12

ゲーム開発をしていると往々にして、とりあえずすぐにFPSを画面に出したいことがあります。
そういう時に以下のコードをプロジェクトに追加することでOnGUIで表示してくれます。

using System.Linq;
using UnityEngine;

public class PerformanceMeasure : MonoBehaviour
{
    static PerformanceMeasure Instance;
    
    const float MeasureInterval = 1.0f;
    const int AveNum = 10;
    
    float nextTime;
    int frameCount, measureCount;
    
    float fps, aveFps;
    readonly float[] fpsHistory = new float[AveNum];

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    static void Create()
    {
        if(Instance) return;
        
        var go = new GameObject();
        Instance = go.AddComponent<PerformanceMeasure>();
        DontDestroyOnLoad(go);
    }
    
    void Update()
    {
        frameCount++;
        if (nextTime > Time.fixedTime) return;
        
        fps = frameCount / MeasureInterval;
        fpsHistory[measureCount] = fps;
        aveFps = fpsHistory.Average();

        nextTime = Time.fixedTime + MeasureInterval;
        frameCount = 0;

        measureCount++;
        if (measureCount >= AveNum) measureCount = 0;
    }

    [SerializeField] float x = 5;
    [SerializeField] float y = 5;
    [SerializeField] float w = 200;
    [SerializeField] float h = 20;
    [SerializeField] float i = 0;

    void OnGUI()
    {
        GUI.Label(new Rect(x, y, w, h), $"FPS:{fps}");
        GUI.Label(new Rect(x, y + h + i, w, h), $"Ave10sFPS:{aveFps}");
    }
}

RuntimeInitializeOnLoadMethodでゲーム起動時に自動でGameObjectを作るため、コードをプロジェクトに追加するだけで動きます。

上記のコードではOnGUIを使って最小限の情報を表示しているため、細かいレイアウトの調整や他UIとの連携などが面倒くさいです。
急ぎでない方はSRDebuggerなどの汎用的なデバッグツールを使うか、自前で多機能の表示を作ってみてください。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?