Unity Test Tip: how to speedup your tests with one simple trick

Game developers need to rely on a fairly large battery of tests to ensure recent changes didn’t break anything. The drawback of such a large number of tests is the time it takes to complete. But what if we could speed them up with one simple trick?

Introducing Time.timeScale

Time shifting always has been an interesting mechanic in video games. You can find it in titles like the indie game Braid, the appropriately named TimeShift, or more recently Superhot.

In Unity, it is the Time.timeScale parameter which allows you to implement this kind of feature. Of course most of the time, this will be used for slow motion, i.e. making the game run at a slower pace.

But the opposite works too, you can make the game run faster if you increase the value of Time.timeScale instead of lowering it. Simply set Time.timeScale to a value higher than 1 in the Setup method of your tests, and they will run faster without any change!

What about waits ?

During tests, explicit waits are sometimes necessary. How are those affected by Time.timeScale? If we read the documentation of the WaitForSeconds class we can see the following sentence:

The real time suspended is equal to the given time divided by Time.timeScale.

So if you write your waits correctly, they should be affected by Time.timeScale appropriately, and you won’t need to change anything.

How fast can your tests run?

Most games aim for a frame rate of 60 FPS, but 30 is an acceptable degraded number.

With that in mind, using Time.timeScale = 2f; is probably good enough and shouldn’t affect your tests. Beyond this number one might expect the tests to become flaky.

However, if you try this trick and your tests fail, it can be the sign of frame rate dependent code. This is not a good thing as you can’t guarantee the frame rate your players will experience on their hardware. To fix that you need to write frame rate independent updates with Time.deltaTime.

I hope this tip will be useful to anyone writing Unity tests, as it can seriously improve the duration of their execution, especially on CI/CD platforms like Game Conductor.

This article was updated on May 14, 2021