Unity 顯示FPS(C#語言)


直接上腳本了:

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class ShowFPS : MonoBehaviour {
 5     //設置幀率
 6     Application.targetFrameRate = 10; 
 7     public float f_UpdateInterval = 0.5F;
 8 
 9     private float f_LastInterval;
10 
11     private int i_Frames = 0;
12 
13     private float f_Fps;
14 
15     void Start() 
16     {
17         //Application.targetFrameRate=60;
18 
19         f_LastInterval = Time.realtimeSinceStartup;
20 
21         i_Frames = 0;
22     }
23 
24     void OnGUI() 
25     {
26         GUI.Label(new Rect(0, 100, 200, 200), "FPS:" + f_Fps.ToString("f2"));
27     }
28 
29     void Update() 
30     {
31         ++i_Frames;
32 
33         if (Time.realtimeSinceStartup > f_LastInterval + f_UpdateInterval) 
34         {
35             f_Fps = i_Frames / (Time.realtimeSinceStartup - f_LastInterval);
36 
37             i_Frames = 0;
38 
39             f_LastInterval = Time.realtimeSinceStartup;
40         }
41     }
42 }

 拿一個別人的帶注釋的:

以備之后用,

// 幀數計算器,需要UGUI來顯示,其實可以通過寫在OnGUI中顯示
[RequireComponent(typeof (Text))]
public class FPSCounter : MonoBehaviour
{
    const float fpsMeasurePeriod = 0.5f;    //FPS測量間隔
    private int m_FpsAccumulator = 0;   //幀數累計的數量
    private float m_FpsNextPeriod = 0;  //FPS下一段的間隔
    private int m_CurrentFps;   //當前的幀率
    const string display = "{0} FPS";   //顯示的文字
    private Text m_Text;    //UGUI中Text組件
 
    private void Start()
    {
        m_FpsNextPeriod = Time.realtimeSinceStartup + fpsMeasurePeriod; //Time.realtimeSinceStartup獲取游戲開始到當前的時間,增加一個測量間隔,計算出下一次幀率計算是要在什么時候
        m_Text = GetComponent<Text>();
    }
 
 
    private void Update()
    {
        // 測量每一秒的平均幀率
        m_FpsAccumulator++;
        if (Time.realtimeSinceStartup > m_FpsNextPeriod)    //當前時間超過了下一次的計算時間
        {
            m_CurrentFps = (int) (m_FpsAccumulator/fpsMeasurePeriod);   //計算
            m_FpsAccumulator = 0;   //計數器歸零
            m_FpsNextPeriod += fpsMeasurePeriod;    //在增加下一次的間隔
            m_Text.text = string.Format(display, m_CurrentFps); //處理一下文字顯示
        }
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM