Search code examples
unity-game-enginescriptingeditorondestroyscriptable-object

Unity (Custom Editor) Save Data When Exit Unity


I created a simple Custom Editor that shows how much time I spent on Unity. When the button on it is pressed, it records the start time in a Scriptable Object (It's dirty). When the button is pressed again, it records the end time. If the window is closed before the button is pressed, I use the OnDestroy() method to complete the recording. It works (I also use "ExecuteInEditMode"). Here is the problem: If I close Unity without pressing the button, the OnDestroy() method does not work this time. Is there any way to fix this?


Solution

  • You could add a callback to EditorApplication.quitting

    Unity raises this event when the editor application is quitting.

    Add an event handler to this event to receive a notification that the application is quitting.

    Note that this will not fire if the Editor is forced to quit or if there is a crash. This event is raised when the quitting process cannot be cancelled.

    Note btw that you could do it completely automated without a button or a ScriptableObject:

    using UnityEngine;
    using UnityEditor;
    using System.Diagnostics;
    
    public static class LogEditorTime
    {
        private static bool isLogging;
        private static readonly StopWatch sw = new StopWatch ();
    
        static void OnQuit()
        {
            sw.Stop();
            var elapsedTime = sw.Elapsed;
    
            Debug.Log($"Quitting the Editor after {elapsedTime.Hours}h {elapsedTime.Minutes}m {elapsedTime.Seconds}.{elapsedTime.Milliseconds / 10}s");
        }
    
        [InitializeOnLoadMethod]
        static void OnLoad()
        {
            if(isLogging) return;
    
            sw.Restart();
    
            EditorApplication.quitting -= OnQuit;
            EditorApplication.quitting += OnQuit;
    
            isLogging = true;
        }
    }