欢迎光临散文网 会员登陆 & 注册

FPS Script

2020-09-14 15:39 作者:unity_某某师_高锦锦  | 我要投稿

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using System;

using TMPro;

public class FPSCounter : MonoBehaviour

{

//Reference to UI to show elasped time

    public TextMeshProUGUI measureTime;


//References to current,min,max and avg fps

    public TextMeshProUGUI current;

    public TextMeshProUGUI min;

    public TextMeshProUGUI max;

    public TextMeshProUGUI avg;


//floats to cache values

    float minFps;

    float avgFps;

    float maxFps;


//List of cached readings to calclulcate avg,max...etc

    List<float> fpsCounts = new List<float>();


//Time to wait to read fps to avoid unnessesary reads

    public float queryRate;

//Decimal places to format readings

    public int roundDecimals = 1;

//cache elapsedTime

    float elapsedTime;

//bools to control how fps is queried

    bool isFps=true;

    bool isStart;

    [Tooltip("Seconds to measure FPS")]

//time to query fps in general. Stops quering after this //duration has elasped

    public float measureSeconds = 10;


    public void StartTimer()

    {

        isStart = true;

    }


    void Update()

    {

        if (isStart)

        {

            elapsedTime += Time.deltaTime;

            if (elapsedTime <= measureSeconds)

            {

                if (isFps)

                {

                    StartCoroutine(QueryFPS());

                    isFps = false;

                }

                measureTime.text = "Elapsed Time: " + Mathf.RoundToInt(elapsedTime) + " s";

            }

            else

            {

                measureTime.transform.GetComponent<Animator>().enabled = true;

            }

        }

    }


    IEnumerator QueryFPS()

    {

        yield return new WaitForSeconds(queryRate);

/*

Delta time is time taken to render a single frame of the game. So its inverse should give us frames rendered in a second

*/

        float reading=1 / Time.deltaTime;

//Add to the list

        fpsCounts.Add(reading);


//Find min and max

        maxFps=Mathf.Max(fpsCounts.ToArray());

        minFps=Mathf.Min(fpsCounts.ToArray());

//Loop to find average

        for (int i = 0; i < fpsCounts.Count; i++)

        {

            avgFps += fpsCounts[i];

        }

//Fill values on UI Components

        current.text = "" + Math.Round(reading, roundDecimals) + " FPS";

        max.text=""+Math.Round(maxFps,roundDecimals)+" FPS";

        min.text = "" + Math.Round(minFps,roundDecimals) + " FPS";

        avg.text = "" + Math.Round((avgFps / fpsCounts.Count),roundDecimals) + " FPS";

        

//Reset averages and bool

        avgFps = 0;

        isFps = true;

    }

}


FPS Script的评论 (共 条)

分享到微博请遵守国家法律