In this lesson, you will learn how to stabilize your game's performance and reduce hardware strain by capping the target frame rate using Application.targetFrameRate.
Why Cap Your Frame Rate?
By default, Unity tries to run your game as fast as your hardware allows. If your game is simple, it might hit hundreds of frames per second (FPS). While a high frame rate sounds good, running at maximum speed forces your CPU and GPU to work as hard as possible, which can cause your device to overheat, drain batteries quickly, and create inconsistent performance.
More importantly, extreme frame rate fluctuations—where your game jumps between 60 and 300 FPS—can make movement feel "jittery" even if you are using Time.deltaTime. By setting a fixed cap, you ensure the simulation runs at a predictable, consistent speed.
Implementing the Frame Rate Cap
You can control this behavior through code, typically inside the Awake() method of a script attached to a manager object. Setting Application.targetFrameRate to -1 tells Unity to run as fast as possible (the default), while setting it to a positive integer forces the engine to wait until enough time has passed to maintain that specific limit.
using UnityEngine;
public class PerformanceManager : MonoBehaviour
{
void Awake()
{
// Cap the game to 60 frames per second
Application.targetFrameRate = 60;
}
}
The Result
When you set Application.targetFrameRate = 60;, Unity will attempt to space out each frame to hit exactly 60 FPS. This not only keeps your simulation logic steady but also gives your CPU and GPU a "breather" between frames. This idle time prevents unnecessary heat generation and ensures your game behaves similarly across different players' computers, regardless of whether they have a low-end laptop or a high-end gaming PC.
Remember that while capping the frame rate provides stability, you should always continue using Time.deltaTime for movement and logic to ensure your game remains independent of whatever frame rate the user ultimately experiences.
Key Takeaway: Use Application.targetFrameRate to set a consistent refresh limit, which stabilizes your game’s simulation and prevents your hardware from working harder than necessary.