using UnityEngine;
///
/// Caps the frame rate via . VSync is
/// disabled automatically while limiting, because it would otherwise override
/// targetFrameRate. Changes apply live (also in Play mode) via OnValidate.
///
[DisallowMultipleComponent]
public class FrameRateLimiter : MonoBehaviour
{
[Header("Limit")]
[Tooltip("Cap the frame rate to 'Target FPS' (off = unlimited).")]
public bool limitFrameRate = true;
[Tooltip("Target frame rate when the limit is active.")]
[Range(1, 360)]
public int targetFps = 60;
[Header("VSync")]
[Tooltip("Disable VSync while limiting (VSync would otherwise override the FPS limit). Normally ON.")]
public bool disableVSyncWhenLimiting = true;
[Tooltip("VSync count when no limit is active (0 = off, 1 = every refresh, 2 = every second refresh).")]
[Range(0, 2)]
public int vSyncCountWhenUnlimited = 0;
void OnEnable() => Apply();
void OnValidate()
{
if (Application.isPlaying)
Apply();
}
/// Applies the current FPS + VSync settings.
public void Apply()
{
if (limitFrameRate)
{
if (disableVSyncWhenLimiting)
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = Mathf.Max(1, targetFps);
}
else
{
QualitySettings.vSyncCount = vSyncCountWhenUnlimited;
Application.targetFrameRate = -1;
}
}
/// 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();
}
}