Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Adaptive Quality Script For Unity and HTC Vive
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// This class in conjunction with the Adaptive Viewport class implements a basic adaptive quality mechanism in Unity.
/// </summary>
public class AdaptiveQuality : MonoBehaviour {
[SerializeField]
private int minQualityLevel = 0;
[SerializeField]
private int maxQualityLevel = 5;
[SerializeField]
private int startQualityLevel = 5;
[SerializeField]
private bool debugQualityLevel = false;
private bool startupFinished = false;
private const int targetFPS = 90;
public delegate void QualityChangedEvent(int newQuality, int previousQuality);
public event QualityChangedEvent QualityChanged;
public int qualityLevel { get; private set; }
public float lastFPS { get; private set; }
private const float updateInterval = 1f;
private int framesCount;
private float framesTime;
private float thisFPS;
private const int maxLastFrames = 7;
private Queue<float> lastFrames = new Queue<float>();
[SerializeField]
private Camera adaptiveCamera;
private void Awake()
{
Messenger<int>.AddListener(StartupFinishEvent.STARTUP_FINISHED, OnLoadingUpdated);
}
private void OnDestroy()
{
Messenger<int>.RemoveListener(StartupFinishEvent.STARTUP_FINISHED, OnLoadingUpdated);
}
private void OnEnable()
{
qualityLevel = startQualityLevel;
QualityChanged(qualityLevel, qualityLevel);
lastFPS = 90.0f;
}
void Update () {
if (startupFinished) {
getFPS();
}
}
void UpdateAdaptiveQuality()
{
if (lastFPS > targetFPS - 15)
{
UpdateQualityLevel(1);
} else if (lastFPS < targetFPS - 15)
{
UpdateQualityLevel(-1);
}
else if (lastFPS < targetFPS - 30)
{
UpdateQualityLevel(-2);
}
}
void UpdateQualityLevel(int delta)
{
int prevQualityLevel = qualityLevel;
qualityLevel = Mathf.Clamp(qualityLevel + delta, minQualityLevel, maxQualityLevel);
if (qualityLevel != prevQualityLevel)
{
if (QualityChanged != null)
{
if (debugQualityLevel)
{
Debug.Log("Changed QualityLevel: " + qualityLevel);
}
QualityChanged(qualityLevel, prevQualityLevel);
}
}
}
void getFPS()
{
framesCount++;
framesTime += Time.unscaledDeltaTime;
if (framesTime > updateInterval)
{
lastFrames.Enqueue(framesCount / framesTime);
if (lastFrames.Count > maxLastFrames)
{
lastFrames.Dequeue();
}
foreach (var frameFPS in lastFrames)
{
thisFPS += frameFPS;
}
lastFPS = thisFPS / lastFrames.Count;
if (debugQualityLevel)
{
Debug.Log("lastFPS: " + lastFPS);
Debug.Log("QualityLevel: " + qualityLevel);
}
thisFPS = 0.0f;
framesCount = 0;
framesTime = 0;
UpdateAdaptiveQuality();
}
}
private void OnLoadingUpdated(int sceneNumber)
{
if (sceneNumber <= 0)
{
startupFinished = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.