FPSCalc——简单FPS观测类

利用Unity做的手游项目很多时候要保证流畅度,流畅度最直观的表现就是帧率FPS。Unity编辑器模式下的帧率观测几乎没有意义,所以还是自己实现的好。

这里给一个前人写的类,我几乎原封不动,该类只有一个对外设置显示和隐藏的接口,并没有提供其他多余操作。

using UnityEngine;
using System.Collections;

/// <summary>
/// FPS calculate.
/// </summary>
public class FPSCalc : MonoSingleton<FPSCalc>
{
    public bool ShowFPS = false;

    public float updateInterval = 0.1f;
    private float lastInterval;
    private int frames = 0;
    private float fps;


    public void SetVisible(bool visible)
    {
        if (instance.ShowFPS != visible)
        {
            instance.ShowFPS = visible;
        }
    }

    void Start()
    {
        lastInterval = Time.realtimeSinceStartup;
        frames = 0;
    }

    void OnGUI()
    {
        if (ShowFPS)
        {
            if (fps > 30f)
                GUI.color = Color.green;
            else if (fps > 15f)
                GUI.color = Color.yellow;
            else
                GUI.color = Color.red;

            GUILayout.Label(fps.ToString("f0"));
        }
    }

    void Update()
    {
        if (ShowFPS)
        {
            ++frames;
            float timeNow = Time.realtimeSinceStartup;
            if (timeNow > lastInterval + updateInterval)
            {
                fps = (float)frames / (timeNow - lastInterval);
                frames = 0;
                lastInterval = timeNow;
            }
        }
    }
}

 

posted on 2016-10-04 13:13  毛尹航  阅读(282)  评论(0编辑  收藏  举报