using UnityEngine;
///
/// Limits the game's frame rate.
///
/// Sets and adjusts VSync
/// () accordingly. IMPORTANT: as long as
/// VSync is active, Unity ignores targetFrameRate - the limit then only takes
/// effect when VSync is off. This script therefore disables VSync automatically
/// as soon as an FPS limit is set (see ).
///
/// Changes apply live: in the editor via OnValidate (also in Play mode while
/// tweaking values in the Inspector).
///
/// Simply attach to any (ideally persistent) GameObject in the scene.
///
[DisallowMultipleComponent]
public class FrameRateLimiter : MonoBehaviour
{
[Header("Limit")]
[Tooltip("ON = the frame rate is capped to 'Target FPS'. OFF = unlimited " +
"(targetFrameRate = -1, platform default).")]
public bool limitFrameRate = true;
[Tooltip("Target frame rate in frames per second when the limit is active.")]
[Range(1, 360)]
public int targetFps = 60;
[Header("VSync")]
[Tooltip("When an FPS limit is set, disable VSync automatically. " +
"Otherwise VSync would override targetFrameRate and the limit " +
"would have no effect. Normally leave this ON.")]
public bool disableVSyncWhenLimiting = true;
[Tooltip("VSync count to use when NO limit is active " +
"(0 = VSync off, 1 = every screen refresh, 2 = every second refresh).")]
[Range(0, 2)]
public int vSyncCountWhenUnlimited = 0;
void OnEnable()
{
Apply();
}
void OnValidate()
{
// Live adjustment when changing values in the Inspector (also in Play mode).
if (Application.isPlaying)
Apply();
}
///
/// Applies the current limit (FPS + VSync) to the Unity settings.
/// Can also be called externally.
///
public void Apply()
{
if (limitFrameRate)
{
if (disableVSyncWhenLimiting)
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = Mathf.Max(1, targetFps);
}
else
{
QualitySettings.vSyncCount = vSyncCountWhenUnlimited;
Application.targetFrameRate = -1; // platform default / unlimited
}
}
/// Enable/disable the limit (e.g. for UI buttons).
public void SetLimitEnabled(bool enabled)
{
limitFrameRate = enabled;
Apply();
}
/// Set the target FPS and enable the limit (e.g. for UI sliders).
public void SetTargetFps(int fps)
{
targetFps = Mathf.Max(1, fps);
limitFrameRate = true;
Apply();
}
}