Skip to content

Instantly share code, notes, and snippets.

@koster
Created December 7, 2024 19:30
Show Gist options
  • Save koster/bbafbaffa6f6cb3673b13105f2a6f0f8 to your computer and use it in GitHub Desktop.
Save koster/bbafbaffa6f6cb3673b13105f2a6f0f8 to your computer and use it in GitHub Desktop.
Unity editor script that logs how long it takes for your project to compile and get into play mode
using System;
using UnityEditor;
using UnityEditor.Compilation;
[InitializeOnLoad]
public static class CompileTimeLogger
{
private const string CompileStartTimeKey = "CompileStartTime";
private const string PlayModeTimerKey = "PlayModeStartTime";
static CompileTimeLogger()
{
// Subscribe to compilation events
CompilationPipeline.compilationStarted += OnCompilationStarted;
CompilationPipeline.compilationFinished += OnCompilationFinished;
// Subscribe to Play Mode events
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
}
// Compilation Timing
private static void OnCompilationStarted(object o)
{
// Save the start time for compilation
EditorPrefs.SetString(CompileStartTimeKey, DateTime.Now.ToString());
UnityEngine.Debug.Log($"{o} Compilation started...");
}
private static void OnCompilationFinished(object o)
{
// Calculate elapsed time using the persisted start time
if (EditorPrefs.HasKey(CompileStartTimeKey))
{
var startTime = DateTime.Parse(EditorPrefs.GetString(CompileStartTimeKey));
var elapsed = DateTime.Now.Ticks - startTime.Ticks;
UnityEngine.Debug.Log($"{o} Compilation finished. Time taken: {TimeSpan.FromTicks(elapsed).TotalMilliseconds} ms");
}
else
{
UnityEngine.Debug.Log("Compilation finished, but start time was not recorded.");
}
}
// Play Mode Timing
private static void OnPlayModeStateChanged(PlayModeStateChange state)
{
switch (state)
{
case PlayModeStateChange.ExitingEditMode:
// Save the current time to persist across domain reloads
EditorPrefs.SetString(PlayModeTimerKey, DateTime.Now.ToString());
UnityEngine.Debug.Log("Exiting Edit Mode... Starting Play Mode timer.");
break;
case PlayModeStateChange.EnteredPlayMode:
// Calculate elapsed time using the persisted start time
if (EditorPrefs.HasKey(PlayModeTimerKey))
{
var startTime = DateTime.Parse(EditorPrefs.GetString(PlayModeTimerKey));
var elapsed = DateTime.Now.Ticks - startTime.Ticks;
UnityEngine.Debug.Log($"Entered Play Mode. Time taken: {TimeSpan.FromTicks(elapsed).TotalMilliseconds} ms");
}
else
{
UnityEngine.Debug.Log("Entered Play Mode, but start time was not recorded.");
}
break;
case PlayModeStateChange.ExitingPlayMode:
UnityEngine.Debug.Log("Exiting Play Mode...");
break;
case PlayModeStateChange.EnteredEditMode:
UnityEngine.Debug.Log("Entered Edit Mode.");
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment