1. 程式人生 > >Unity3d 幀率設定 及在遊戲執行時顯示幀率

Unity3d 幀率設定 及在遊戲執行時顯示幀率

在Unity3d 中可以通過程式碼設定 來限定遊戲幀率。

Application.targetFrameRate=-1;

設定為 -1 表示不限定幀率。 轉自http://blog.csdn.net/huutu

一般在手機遊戲中我們限定幀率為30 就OK了。

Application.targetFrameRate=30;

但是把這個程式碼新增到工程之後,在Unity中執行起來發現並沒有什麼卵用。。。。

轉自http://blog.csdn.net/huutu

於是到官網檢視資料

http://docs.unity3d.com/ScriptReference/Application-targetFrameRate.html

Application.targetFrameRate
public static int targetFrameRate;
Description

Instructs game to try to render at a specified frame rate.

Setting targetFrameRate to -1 (the default) makes standalone games render as fast as they can, 

and web player games to render at 50-60 frames/second depending on the platform.

Note that setting targetFrameRate does not guarantee that frame rate. 

There can be fluctuations due to platform specifics, or the game might not achieve the frame rate because the computer is too slow.

If vsync is set in quality setting, the target framerate is ignored, and the vblank interval is used instead. 

The vBlankCount property on qualitysettings can be used to limit the framerate to half of the screens refresh rate 

(60 fps screen can be limited to 30 fps by setting vBlankCount to 2)

targetFrameRate is ignored in the editor.

大意就是說:

Application.targetFrameRate 是用來讓遊戲以指定的幀率執行,如果設定為 -1 就讓遊戲以最快的速度執行。

但是 這個 設定會 垂直同步 影響。

如果設定了垂直同步,那麼 就會拋棄這個設定 而根據 螢幕硬體的重新整理速度來執行。

如果設定了垂直同步為1,那麼就是 60 幀。

如果設定了為2 ,那麼就是 30 幀。

點選 選單  Editor -> ProjectSetting -> QualitySettings 來開啟渲染質量設定面板。

轉自http://blog.csdn.net/huutu

1、首先關掉垂直同步,如上圖。

設定幀率為100

然後執行後的幀率是 100.

2、設定垂直同步為1

可以看到幀率為 60 幀左右跳動,完全無視了程式碼中的設定。

轉自http://blog.csdn.net/huutu

3、設定垂直同步為 2

可以看到幀率在 30幀左右跳動。

轉自http://blog.csdn.net/huutu

在遊戲中顯示幀率程式碼:

using UnityEngine;
using System.Collections;
using DG.Tweening;

public class NewBehaviourScript : MonoBehaviour 
{
	private float m_LastUpdateShowTime=0f;	//上一次更新幀率的時間;

	private float m_UpdateShowDeltaTime=0.01f;//更新幀率的時間間隔;

	private int m_FrameUpdate=0;//幀數;

	private float m_FPS=0;

	void Awake()
	{
		Application.targetFrameRate=100;
	}

	// Use this for initialization
	void Start () 
	{
		m_LastUpdateShowTime=Time.realtimeSinceStartup;
	}
	
	// Update is called once per frame
	void Update () 
	{
		m_FrameUpdate++;
		if(Time.realtimeSinceStartup-m_LastUpdateShowTime>=m_UpdateShowDeltaTime)
		{
			m_FPS=m_FrameUpdate/(Time.realtimeSinceStartup-m_LastUpdateShowTime);
			m_FrameUpdate=0;
			m_LastUpdateShowTime=Time.realtimeSinceStartup;
		}
	}

	void OnGUI()
	{
		GUI.Label(new Rect(Screen.width/2,0,100,100),"FPS: "+m_FPS);
	}
}

官網文件中的最後一句……經測試在編輯器狀態下是有效的。。