unity中獲取FPS

1.獲取適合時間內的FPS平均值,此處爲0.5s內的平均幀數

 public class FPS : MonoBehaviour
 {
 public UnityEngine.UI.Text textObj_fps;
 public bool showFPS = true;
 private float updateInterval = 0.5f;
 private float accum = 0.0f; // FPS accumulated over the interval
 private float frames  = 0f; // Frames drawn over the interval
 private float timeleft; // Left time for current interval

 void Start () {
  InvokeRepeating("SetType",0.1f,0.5f);
 }
 void LateUpdate () {
  // CALCULATE FPS
  if (showFPS){
      timeleft -= Time.deltaTime;
      accum += Time.timeScale/Time.deltaTime;
      ++frames;
    
      // Interval ended - update GUI text and start new interval
      if( timeleft <= 0.0f )
      {
          // display two fractional digits (f2 format)
          timeleft = updateInterval;
          accum = 0.0f;
          frames = 0f;
      }
  } else {
   textObj_fps.text = "";
  }
 }

 void SetType(){
     if (textObj_fps != null &&  accum > 0f && frames > 0f){
      textObj_fps.text = "FPS: "+(accum/frames).ToString("f0");
  }
 }
}
2.獲取當前FPS,此時獲取頻率可加大
 public class FPS : MonoBehaviour
 {
 public UnityEngine.UI.Text textObj_fps;
 void Start () {
  InvokeRepeating("SetType",0.1f,0.1f);
 }

 void SetType(){
     if (textObj_fps != null){
            textObj_fps.text = "FPS: " + (Time.timeScale / Time.deltaTime).ToString("f0");
  }
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章