Unity(自定义编辑器)退出Unity时保存数据
Unity (Custom Editor) Save Data When Exit Unity
我创建了一个简单的自定义编辑器来显示我在 Unity 上花费了多少时间。当按下按钮时,它会在可编写脚本的对象(它很脏)中记录开始时间。再次按下按钮时,它会记录结束时间。如果 window 在按下按钮之前关闭,我使用 OnDestroy() 方法来完成录制。它有效(我也使用“ExecuteInEditMode”)。
问题是:如果我不按按钮就关闭 Unity,这次 OnDestroy() 方法不起作用。有什么办法可以解决这个问题吗?
您可以向 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.
顺便说一下,您可以在没有按钮或 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;
}
}
我创建了一个简单的自定义编辑器来显示我在 Unity 上花费了多少时间。当按下按钮时,它会在可编写脚本的对象(它很脏)中记录开始时间。再次按下按钮时,它会记录结束时间。如果 window 在按下按钮之前关闭,我使用 OnDestroy() 方法来完成录制。它有效(我也使用“ExecuteInEditMode”)。 问题是:如果我不按按钮就关闭 Unity,这次 OnDestroy() 方法不起作用。有什么办法可以解决这个问题吗?
您可以向 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.
顺便说一下,您可以在没有按钮或 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;
}
}