Unity 关闭程序

发布时间:2026/7/17 5:36:59
Unity 关闭程序 时间2026.07版本Unity 6000.3.19f1说明点击右上角的关闭按钮时会弹出一个确认框进行二次确认将该脚本挂在到一个空物体上即可使用。using System; using System.Runtime.InteropServices; using UnityEngine; public class ApplicationQuit : MonoBehaviour { #region variable /// summary 用于告诉Unity是否要退出 /summary private bool m_IsWantsToQuit false; /// summary 判断是否点击了退出程序按钮 /summary private bool m_IsClickCloseBtn false; /// summary 用于执行退出前的委托 /summary private Action m_WantsToQuitAction; #endregion [DllImport(User32.dll, SetLastError true, ThrowOnUnmappableChar true, CharSet CharSet.Auto)] public static extern int MessageBox(IntPtr handle, String message, String title, int type); private void Awake() { m_IsWantsToQuit false; m_IsClickCloseBtn false; Application.wantsToQuit WantsToQuit; } private void Start() { m_WantsToQuitAction () ShowMessageBox(); } private bool WantsToQuit() { if (!m_IsWantsToQuit !m_IsClickCloseBtn) m_WantsToQuitAction?.Invoke(); return m_IsWantsToQuit; } private void ShowMessageBox() { #if !UNITY_EDITOR m_IsClickCloseBtn true; int messageIndex MessageBox(IntPtr.Zero, 确定要退出程序吗, 提示, 1); if (messageIndex 1) { m_IsWantsToQuit true; Application.Quit(); // 杀死当前进程强制关闭 System.Diagnostics.Process.GetCurrentProcess().Kill(); } else { m_IsClickCloseBtn false; } #endif } }