Skip to content

Instantly share code, notes, and snippets.

@oktomus
Created March 30, 2023 11:04
Show Gist options
  • Save oktomus/9dbe12587dfd4687d8cc60c97f816494 to your computer and use it in GitHub Desktop.
Save oktomus/9dbe12587dfd4687d8cc60c97f816494 to your computer and use it in GitHub Desktop.
Monitor time taken to recompile scripts in Unity and log it
using System;
using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;
public static class ScriptCompilationTime
{
private const string FileName = ".AssemblyReloadStarted.txt";
private static readonly string FilePath = Path.Combine(Application.dataPath, FileName);
[DidReloadScripts]
private static void OnScriptsReloaded()
{
// This code will run after assembly reloading is complete.
// Debug.Log("OnScriptsReloaded at " + DateTime.Now.ToString("HH:mm:ss.fff"));
// Wait for end of compilation.
EditorApplication.delayCall += () =>
{
// Unserialize the start time.
var lines = File.ReadAllLines(FilePath);
var lastLine = lines[^1];
var startTime = DateTime.Parse(lastLine);
var compileTime = DateTime.Now - startTime;
// Log the time it took once the compilation is done
Debug.Log($"Script compilation took {compileTime.TotalSeconds:F2} seconds");
};
}
[InitializeOnLoadMethod]
private static void RegisterAssemblyReloadEvents()
{
// Debug.Log("Registering assembly reload events at " + DateTime.Now.ToString("HH:mm:ss.fff"));
AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload;
}
private static void OnBeforeAssemblyReload()
{
AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload;
// Debug.Log("OnBeforeAssemblyReload at " + DateTime.Now.ToString("HH:mm:ss.fff"));
// This code will run just before assembly reloading starts.
// Write a timestamp to a file before the script compilation starts
using var writer = new StreamWriter(FilePath, false);
writer.WriteLine(DateTime.Now);
writer.Flush();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment