需求方要求在退出之前让用户点击确认按钮,不想做大的改动,查了一下网上都是说用Application.CancelQuit,但是貌似Unity2018以后就没法用了提示这个类已经过时,推荐使用WantsToQuit。

因此来简单写了个工具类。
用法很简单,注释也很详细,就不多说了,使用方法如下:
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
//退出窗口
public GameObject m_Panel;
public Button m_Panel_CloseButton;
public Button m_Panel_QuitButton;
// Start is called before the first frame update
void Start()
{
//默认关闭窗口
OpenClosePanel(false);
//QuitHelp委托,当用户想退出时打开窗口
QuitHelp.WantsToQuitActions += () => OpenClosePanel(true);
//关闭确认退出窗口
m_Panel_CloseButton.onClick.AddListener(() => OpenClosePanel(false));
//确认退出
m_Panel_QuitButton.onClick.AddListener(() =>
{
QuitHelp.IsWantsToQuit = true;
Application.Quit();
}
);
}
//开关确认退出窗口
public void OpenClosePanel(bool isopen = false)
{
m_Panel.SetActive(isopen);
}
}
创建一个简单的panel和两个按钮,赋值给测试脚本。

工具类如下:
using System;
using UnityEngine;
public class QuitHelp
{
//程序启动默认执行
[RuntimeInitializeOnLoadMethod]
private static void RunOnStart()
{
Application.wantsToQuit += WantsToQuit;
}
private static bool m_IsWantsToQuit = false;//用于告诉Unity是否要退出
private static Action m_WantsToQuitActions;//用于执行退出前的委托
public static bool IsWantsToQuit { get => m_IsWantsToQuit; set => m_IsWantsToQuit = value; }
public static Action WantsToQuitActions { get => m_WantsToQuitActions; set => m_WantsToQuitActions = value; }
//用户想退出的时候Unity会回调这个委托
private static bool WantsToQuit()
{
if (!IsWantsToQuit)
WantsToQuitActions();
return IsWantsToQuit;
}
}
另外这个委托在macOS、win、安卓(退出键)上都会调用,ios不会调用,测试时注意设置为窗口,否则全屏就没有退出按钮啦~。
实测在一些32位电脑上会出现问题,建议写一个宏定义,或者直接移除此功能。
网友评论