直接上脚本了:
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); //处理一下文字显示 } } }