Files
chameleon/Assets/Scripts/FrameRateLimiter.cs
T
adminandClaude Opus 4.8 f758c96dc5 Trim comments and use implicit null checks for Unity objects
Reduce comments to non-obvious "why" notes and convert UnityEngine.Object
null checks to implicit bool (if (obj) / if (!obj)). Input System devices
(Mouse.current, Keyboard.current) and plain arrays keep explicit != null.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 17:26:41 +02:00

67 lines
1.9 KiB
C#

using UnityEngine;
/// <summary>
/// Caps the frame rate via <see cref="Application.targetFrameRate"/>. VSync is
/// disabled automatically while limiting, because it would otherwise override
/// targetFrameRate. Changes apply live (also in Play mode) via OnValidate.
/// </summary>
[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();
}
/// <summary>Applies the current FPS + VSync settings.</summary>
public void Apply()
{
if (limitFrameRate)
{
if (disableVSyncWhenLimiting)
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = Mathf.Max(1, targetFps);
}
else
{
QualitySettings.vSyncCount = vSyncCountWhenUnlimited;
Application.targetFrameRate = -1;
}
}
/// <summary>Enable/disable the limit (e.g. for UI buttons).</summary>
public void SetLimitEnabled(bool enabled)
{
limitFrameRate = enabled;
Apply();
}
/// <summary>Set the target FPS and enable the limit (e.g. for UI sliders).</summary>
public void SetTargetFps(int fps)
{
targetFps = Mathf.Max(1, fps);
limitFrameRate = true;
Apply();
}
}