文档

Unity 引擎

Unity 引擎

模拟测试挂钩

模拟搭桥以测试游戏如何处理由性能问题引起的时间变化。
阅读时间3 分钟最后更新于 7 天前

引入故意卡顿是测试游戏如何处理性性能问题(如Lag尖峰、帧、卡顿或在压力下降低 UI 响应)的常用技术。
以下是一个Simple的 MonoBehaviour 脚本,您可以将其附加到Scene中的Any游戏对象对象。它会导致主要线程定期挂起,从而模拟帧时间的卡顿或峰值。您可以轻松调整测试挂钩的频率和 Duration。
using UnityEngine;using Unity.Profiling;public class HitchSimulator :MonoBehaviour{ Static 只读 ProfilerMarker k_HitchSimulatorMarker = 新建 ProfilerMarker("[HitchSimulator] CauseHitch() introduced artificial hitches"); [工具提示("导致卡顿的频率(以秒为单位)")] public float hitchInterval = 5f; [工具提示("每个绑定应该持续多长时间(以毫秒为单位)")] 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 } }}
要使用脚本:
  1. 将脚本复制到名为
    HitchSimulator.cs
    的新建 C# 文件中。
  2. 将其附加到Scene中的AnyActive游戏对象对象。
  3. 在 Inspector 中设置 Parameters:
    • hitchInterval
      :搭便车的频率。默认值为 5 秒。
    • hitchDurationMs
      :每个挂钩持续多长时间。默认为 200 毫秒。
  4. 进入播放模式并观察性能性能分析器中的故意帧卡顿,或在视觉上表现为卡顿。
注意
此脚本阻止主要线程。它模拟来自繁重计算的真实 Lag 峰值,而不仅仅是人为减速。如果使用非常大的值,这可能make Editor 无响应。您还可以通过按键或随随机触发器,从而进行更耐用、抗变换、鲁棒性的测试。

其他资源

  • Unity Profiler:使用性能分析器 性能分析器 可Monitor游戏在卡滞期间的行为。
  • 性能优化:在 Unity 中优化性性能的General技巧。