Skip to content

Instantly share code, notes, and snippets.

@spajus
Last active May 14, 2020 10:59
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 spajus/1c9e45b8047274f17253cd55d62d244c to your computer and use it in GitHub Desktop.
Save spajus/1c9e45b8047274f17253cd55d62d244c to your computer and use it in GitHub Desktop.
Unity MonoBehaviour that stops the editor play mode before it's too late
using UnityEngine;
using UnityEngine.Profiling;
namespace KL.Utils {
public class FPSHandbrake : MonoBehaviour {
private float stopEditorAtFPS = 5;
private float memoryMaxMB = 1024 * 10;
private float stopEditorDelay = 10;
private float stopFrameDurationTreshold = 1;
private float startFromFrame = 10;
#if UNITY_EDITOR
private int killAfterFrames = -1;
private float timeBelowStopFPS;
private float lastFrameRealTime;
void Start() {
lastFrameRealTime = Time.realtimeSinceStartup;
}
void Update() {
if (!UnityEditor.EditorApplication.isPlaying) { return; }
if (Time.frameCount < startFromFrame) {
lastFrameRealTime = Time.realtimeSinceStartup;
return;
}
var fps = 1f / Time.smoothDeltaTime;
var t = Time.realtimeSinceStartup;
var ft = lastFrameRealTime - t;
lastFrameRealTime = t;
if (ft > stopFrameDurationTreshold) {
Debug.LogErrorFormat(
"Stopping editor play mode in 10 frames from now because of frame duration: {0:0.00}s > {1:0.00}s",
ft, stopFrameDurationTreshold);
if (killAfterFrames < 0) {
killAfterFrames = 10;
return;
}
}
if (killAfterFrames > 0) {
killAfterFrames -= 1;
if (killAfterFrames == 0) {
UnityEditor.EditorApplication.isPlaying = false;
}
}
if (fps < stopEditorAtFPS) {
timeBelowStopFPS += Time.deltaTime;
} else {
timeBelowStopFPS = 0;
}
if (timeBelowStopFPS > stopEditorDelay) {
Debug.LogErrorFormat(
"Stopping editor play mode after running for {0:0.00}s at {1} FPS!",
timeBelowStopFPS, stopEditorAtFPS);
UnityEditor.EditorApplication.isPlaying = false;
}
var mem = MemoryUsedMB();
if (mem > memoryMaxMB) {
Debug.LogErrorFormat(
"Stopping editor play mode: Memory {0} MB > {1} MB",
mem, memoryMaxMB);
UnityEditor.EditorApplication.isPlaying = false;
}
}
private float MemoryUsedMB() {
float m1 = (Profiler.GetTotalAllocatedMemoryLong() / 1024f / 1024f);
float m2 = (Profiler.GetAllocatedMemoryForGraphicsDriver() / 1024f / 1024f);
float m3 = (Profiler.GetTotalReservedMemoryLong() / 1024f / 1024f);
return m1 + m2 + m3;
}
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment