包含此页的版本:
不含此页的版本:
引入故意卡顿是一种常用技术,用于测试游戏在压力下如何处理延迟峰值、掉帧、卡顿或 UI 响应能力下降等性能问题。
下面是一个简单的 MonoBehaviour 脚本,你可以将其附加到任何游戏对象Unity 场景中的基本对象,可以表示角色、道具、风景、相机、航路点等。游戏对象的功能由附加到它的组件定义。更多信息
请参阅术语表在你的场景场景包含游戏的环境和菜单。将每个唯一的场景文件视为一个独特的关卡。在每个场景中,你放置你的环境、障碍物和装饰品,基本上是将你的游戏设计和构建成碎片。更多信息
请参阅术语表.它会导致主线程定期挂起,模拟帧时间的卡顿或峰值。您可以轻松调整测试挂钩的频率和持续时间。
using UnityEngine;
using Unity.Profiling;
public class HitchSimulator : MonoBehaviour
{
static readonly ProfilerMarker k_HitchSimulatorMarker = new ProfilerMarker("[HitchSimulator] CauseHitch() introducing artificial hitches");
[Tooltip("How often (in seconds) to cause a hitch.")]
public float hitchInterval = 5f;
[Tooltip("How long (in milliseconds) each hitch should last.")]
public int hitchDurationMs = 200;
private float _nextHitchTime = 0f;
void Update()
{
if (Time.time >= _nextHitchTime)
{
Debug.LogWarning($"[HitchSimulator] Causing a hitch for {hitchDurationMs} ms at {Time.time:F2}s");
CauseHitch(hitchDurationMs);
_nextHitchTime = Time.time + hitchInterval;
}
}
void CauseHitch(int durationMs)
{
// Adding a clarifying profiler marker so no one accidentally confuses this for an actual issue.
k_HitchSimulatorMarker.Auto();
float start = Time.realtimeSinceStartup;
// Busy wait for the specified duration
while ((Time.realtimeSinceStartup - start) < durationMs / 1000f)
{
// Just spin
}
}
}
要使用脚本,请执行以下作:
HitchSimulator.cs.hitchInterval:搭便车的频率。默认值为 5 秒。hitchDurationMs:每个挂钩的持续时间。默认值为 200 毫孔。注意:此脚本会阻止主线程。它模拟了繁重计算带来的真实滞后峰值,而不仅仅是人为的减速。如果使用非常大的值,这可能会使编辑器无响应。您还可以通过按键或随机间隔触发卡顿,以进行更稳健的测试。