Unity3D 帧数修改

2015年01月15日 11:40 0 点赞 0 评论 更新于 2017-05-02 03:46

在 Unity3D 中,我们该如何修改游戏的帧数呢?下面将为大家详细介绍具体的操作步骤。

步骤一:在 Quality(质量)设置里关闭帧数设定

在修改游戏运行帧数之前,我们需要先在 Quality 设置中关闭帧数设定。只有完成这一步,后续才能在代码中对游戏运行的帧数进行修改。

步骤二:编写修改帧数的脚本

在 Unity 中新建一个名为 UpdateFrame.cs 的脚本,并编写以下代码:

using UnityEngine;
using System.Collections;

/// <summary>
/// 功能:修改游戏 FPS
/// </summary>
public class UpdateFrame : MonoBehaviour
{
// 游戏的 FPS,可在属性窗口中修改
public int targetFrameRate = 300;

// 当程序唤醒时
void Awake()
{
// 修改当前的 FPS
Application.targetFrameRate = targetFrameRate;
}
}

在上述代码中,我们定义了一个公共整数变量 targetFrameRate,用于设置目标帧率,默认值为 300。在 Awake 方法中,将 Application.targetFrameRate 设置为 targetFrameRate 的值,从而实现修改游戏帧率的目的。

步骤三:显示当前 FPS 并测试修改结果

1. 编写显示 FPS 的脚本

创建一个名为 ShowFPS.js 的脚本,代码如下:

@script ExecuteInEditMode

private var gui: GUIText;
private var updateInterval = 1.0;
private var lastInterval: double; // Last interval end time
private var frames = 0; // Frames over current interval

function Start()
{
lastInterval = Time.realtimeSinceStartup;
frames = 0;
}

function OnDisable()
{
if (gui)
DestroyImmediate(gui.gameObject);
}

function Update()
{
#if !UNITY_FLASH
++frames;
var timeNow = Time.realtimeSinceStartup;
if (timeNow > lastInterval + updateInterval)
{
if (!gui)
{
var go: GameObject = new GameObject("FPS Display", GUIText);
go.hideFlags = HideFlags.HideAndDontSave;
go.transform.position = Vector3(0, 0, 0);
gui = go.guiText;
gui.pixelOffset = Vector2(5, 55);
}
var fps: float = frames / (timeNow - lastInterval);
var ms: float = 1000.0f / Mathf.Max(fps, 0.00001);
gui.text = ms.ToString("f1") + "ms " + fps.ToString("f2") + "FPS";
frames = 0;
lastInterval = timeNow;
}
#endif
}

这段代码的主要功能是在游戏界面上实时显示当前的 FPS。通过 Start 方法初始化相关变量,在 Update 方法中计算帧率并更新显示内容。

2. 绑定脚本并测试

UpdateFrame.csShowFPS.js 这两个脚本绑定到层次视图中的任意一个 GameObject 上,然后运行游戏。此时,在 Game 视图中就可以看到当前的 FPS。同时,你可以在属性窗口中修改 UpdateFrame.cs 脚本里的 targetFrameRate 变量,观察不同帧率设置下的游戏运行效果。

通过以上步骤,你就可以在 Unity3D 中成功修改游戏的帧数,并实时查看帧率变化了。

作者信息

feifeila

feifeila

共发布了 570 篇文章