Skip to content

Instantly share code, notes, and snippets.

@ruccho
Created February 16, 2020 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruccho/5fe0ff946cbb8d6532d422c4bcb6cda1 to your computer and use it in GitHub Desktop.
Save ruccho/5fe0ff946cbb8d6532d422c4bcb6cda1 to your computer and use it in GitHub Desktop.
using System.Threading;
using UnityEngine;
public class FPSAdjuster : MonoBehaviour
{
[SerializeField, Min(1)]
private int fps;
[SerializeField]
private bool useThreadSleep = false;
private int interval => 1000 / fps;
private int defaultFps;
float prevFrameTime;
void Start()
{
prevFrameTime = Time.realtimeSinceStartup;
defaultFps = Application.targetFrameRate;
}
void Update()
{
if (!useThreadSleep)
{
Application.targetFrameRate = fps;
}
else
{
Application.targetFrameRate = defaultFps;
float frameTime = Time.realtimeSinceStartup;
float delta = frameTime - prevFrameTime;
int requiredInterval = Mathf.RoundToInt(interval - delta * 1000);
if (requiredInterval > 0)
{
Thread.Sleep(requiredInterval);
}
prevFrameTime = Time.realtimeSinceStartup;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment