Is there a way to invoke/simulate Application.wantsToQuit
from the editor in play-mode?
I’m designing an “Are you sure you want to quit?” prompt to appear when the player tries to quit the game. It listens for Application.wantsToQuit to catch the quit attempt and then display the prompt. However, I’m unable to test my implementation from inside the editor because I cannot see how to emit Application.wantsToQuit. Application.Quit() intentionally does nothing in the editor.
I hoped Application.Quit() would still mimic the Application.wantsToQuit event, even if it ultimately ignores the quit request and ignores the return value of wantsToQuit, but the function appears to be a no-op in the editor.
Sorry to disappoint you, but there is not much to do in editor mode, I have this code when a quit decision has been made (i.e no chance of not quitting):
#if UNITY_EDITOR
//Application.Quit() does not work in the editor so
// this need to be set to false to end the game
UnityEditor.EditorApplication.isPlaying = false;
#else
UnityEngine.Application.Quit();
#endif
Not the ideal solution, but I made a wrapper to handle my issue. I subscribe to QuitWrapper.wantsToQuit
in place of Application.wantsToQuit
. Then, when I want to simulate the user quitting, I call QuitWrapper.Quit()
which gives me a chance to respond to the event even during the editor’s play-mode.
using System;
using UnityEngine;
public class QuitWrapper
{
/// <summary>
/// Invoked by calling <see cref="Quit"/>. This is a replacement version of
/// <see cref="Application.wantsToQuit"/> that supports play-mode in the
/// editor.
/// </summary>
public static event Func<bool> wantsToQuit
{
add
{
if (Application.isEditor)
{
m_WantsToQuitEditorPlaymode += value;
}
else
{
Application.wantsToQuit += value;
}
}
remove
{
if (Application.isEditor)
{
m_WantsToQuitEditorPlaymode -= value;
}
else
{
Application.wantsToQuit -= value;
}
}
}
/// <summary>
/// A wrapper for <see cref="Application.Quit"/> that emits the custom
/// <see cref="wantsToQuit"/> event which can be caught and canceled
/// during the editor's play-mode. If the quit request is not canceled,
/// the application will quit / play-mode will end.
/// </summary>
public static void Quit()
{
if (m_WantsToQuitEditorPlaymode != null)
{
foreach (Func<bool> continueQuit in m_WantsToQuitEditorPlaymode.GetInvocationList())
{
try
{
if (!continueQuit())
{
return;
}
}
catch (Exception exception)
{
Debug.LogException(exception);
}
}
}
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
private static event Func<bool> m_WantsToQuitEditorPlaymode;
} // class QuitWrapper