Unity3D设置帧率和显示FPS脚本
发表于2018-09-04
对于一些PC端的FPS游戏来说,游戏帧率跑得越高越好,FPS跑得越高游戏就越流畅,但是在手机端就不行了,游戏帧率过高,会导致CPU和GPU负荷增大,这样手机就会发热过大,影响游戏体验。在大多数情况下,30-60帧的范围就足够了,下面就来看看设置帧率和显示FPS脚本的实现方法。
1、Unity3D设置帧率FPS的方法
3.5以后的版本,可以直接设置Application.targetFrameRate。直接修改脚本就可以了。
using UnityEngine; using System.Collections; public class example : MonoBehaviour { void Awake() { Application.targetFrameRate = 60; } }
默认参数为-1,这个时候所有平台中游戏都会尽可能快地渲染,在WEB平台上最高是50~60帧,当然要你的游戏能达到这个帧率才行。
需要注意的是在Edit/Project Setting/QualitySettings下,若vsync被设置了,则targetFrameRate设置的将无效。两者是冲突关系。
2、显示FPS脚本
/// <summary> /// Set FPS /// this script use to set FPS if platform is mobile /// </summary> using UnityEngine; using System.Collections; using System.Collections.Generic; public class ShowFPS : MonoBehaviour { public int fpsTarget; public float updateInterval = 0.5f; private float lastInterval; private int frames = 0; private float fps; void Start() { //设置帧率 Application.targetFrameRate = 10; lastInterval = Time.realtimeSinceStartup; frames = 0; } // Update is called once per frame void Update() { ++frames; float timeNow = Time.realtimeSinceStartup; if (timeNow >= lastInterval + updateInterval) { fps = frames / (timeNow - lastInterval); frames = 0; lastInterval = timeNow; } } void OnGUI() { GUI.Label(new Rect(200, 40, 100, 30), fps.ToString()); } }