In this lesson, you will learn how to automate performance regression testing to detect frame time spikes before they become critical bottlenecks in your final build.
The Strategy of Automated Performance Testing
By this stage, you have mastered using the Profiler to baseline your project and pinpoint memory leaks or expensive loops. However, manual profiling is prone to human error and is rarely consistent. Automated regression testing replaces "spot checks" with a repeatable script that executes a specific game scene, records performance data, and compares it against your established baseline.
When you integrate these tests into your CI/CD pipeline, the build server runs a "Performance Test" build. If the average frame time or memory allocation exceeds your defined threshold, the build is flagged as a failure, notifying you immediately that a recent code change has introduced a performance regression.
Implementing a Performance Test
You can use the Unity PerformanceTesting package to wrap your gameplay tests. This allows you to measure specific code blocks or overall scene performance during automated runs.
using Unity.PerformanceTesting;
using UnityEngine;
using UnityEngine.TestTools;
using System.Collections;
public class RenderingPerformanceTests
{
[UnityTest, Performance]
public IEnumerator MeasureCombatScenePerformance()
{
// Load the scene and wait for initial loading spike to settle
yield return SceneManager.LoadSceneAsync("CombatArena");
yield return new WaitForSeconds(2.0f);
// Run the performance measure over 100 frames
yield return Measure.Frames().Run();
}
}
In this snippet, the [Performance] attribute instructs the test runner to capture data like CPU time and memory usage. By running this test on the same hardware environment (e.g., a specific build machine), you eliminate variables. If the average frame time shifts from 16ms to 20ms, you know exactly which commit caused the dip, allowing you to debug using the tools you’ve learned, like CPU Profiling or Frame Debugger, long before the game reaches the optimization-heavy final phases.
Key Takeaway: Automating performance tests turns potential optimization nightmares into immediate, actionable alerts, ensuring your performance budget remains strictly enforced throughout development.