描述

用于物理计算且独立于帧率的 MonoBehaviour.FixedUpdate 消息。

MonoBehaviour.FixedUpdate 具有物理系统的频率;每个固定帧率帧调用该函数。在 FixedUpdate 之后,进行 Physics 系统计算。调用之间的默认时间为 0.02 秒(50 次调用/秒)。使用 Time.fixedDeltaTime 来访问该值。变更该值,方法是在脚本内将其设置为所需的值,或者导航到 Edit > Settings > Time > Fixed Timestep,然后在此处对其进行设置。FixedUpdate 频率高于或低于 Update。如果应用程序以 25 帧/秒 (fps) 的速度运行,Unity 大约每帧调用该应用程序两次,或者,100 fps 使每个 FixedUpdate 大约渲染两帧。通过 Time 设置,控制所需帧率以及 Fixed Timestep 速率。使用 Application.targetFrameRate 可以设置帧率。

使用 Rigidbody 时使用 FixedUpdate。将力设置为 Rigidbody,并在每个固定帧应用该力。FixedUpdate 按照测量的时间步长进行,一般不会与 MonoBehaviour.Update 冲突。

在以下示例中,Update 调用次数将与 FixedUpdate 调用次数相比较。FixedUpdate 每秒执行 50 次。(游戏代码在测试机器上的运行速度大约为 200 fps。)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// GameObject.FixedUpdate example. // // Measure frame rate comparing FixedUpdate against Update. // Show the rates every second.

public class ExampleScript : MonoBehaviour { private float updateCount = 0; private float fixedUpdateCount = 0; private float updateUpdateCountPerSecond; private float updateFixedUpdateCountPerSecond;

void Awake() { // Uncommenting this will cause framerate to drop to 10 frames per second. // This will mean that FixedUpdate is called more often than Update. //Application.targetFrameRate = 10; StartCoroutine(Loop()); }

// Increase the number of calls to Update. void Update() { updateCount += 1; }

// Increase the number of calls to FixedUpdate. void FixedUpdate() { fixedUpdateCount += 1; }

// Show the number of calls to both messages. void OnGUI() { GUIStyle fontSize = new GUIStyle(GUI.skin.GetStyle("label")); fontSize.fontSize = 24; GUI.Label(new Rect(100, 100, 200, 50), "Update: " + updateUpdateCountPerSecond.ToString(), fontSize); GUI.Label(new Rect(100, 150, 200, 50), "FixedUpdate: " + updateFixedUpdateCountPerSecond.ToString(), fontSize); }

// Update both CountsPerSecond values every second. IEnumerator Loop() { while (true) { yield return new WaitForSeconds(1); updateUpdateCountPerSecond = updateCount; updateFixedUpdateCountPerSecond = fixedUpdateCount;

updateCount = 0; fixedUpdateCount = 0; } } }