unity FrameCounter

 

개인 저장용.

CircularArray로 쓰면 좋을거 같지만.. 디버깅용이니까 이 정도로도 괜찮을 듯.

 

using System.Collections;
using TMPro;
using UnityEngine;

public class FPSCounter : MonoBehaviour
{
    private const int SAMPLE_SIZE = 20;

    private TextMeshProUGUI _txt_fps;
    private readonly Queue<float> _timeQueue = new Queue<float>();
    private Coroutine _co;

    private void Awake()
    {
        TryGetComponent<TextMeshProUGUI>(out _txt_fps);
    }

    private void OnEnable()
    {
        if (_txt_fps != null)
            _co = StartCoroutine(CountCoroutine());
    }

    private void OnDisable()
    {
        if (_co != null)
            StopCoroutine(_co);
    }

    private IEnumerator CountCoroutine()
    {
        while (true)
        {
            yield return new WaitForSeconds(0.1f);

            _timeQueue.Enqueue(Time.unscaledDeltaTime);
            if (_timeQueue.Count > SAMPLE_SIZE)
                _timeQueue.Dequeue();

            float averageTime = _timeQueue.Average();
            int averageFramePrint = Mathf.RoundToInt(1f / averageTime);
            double averageTimePrint = Math.Round(averageTime * 1000f, 1);

            _txt_fps.text = $"{averageFramePrint} / {averageTimePrint:N1}ms";
        }
    }
}

댓글

Designed by JB FACTORY