处理退出请求

退出

大多数平台都有要求应用程序退出的选项.在台式机上,这通常是通过窗口标题栏上的 “x” 图标来实现的.在安卓系统上,当在主屏幕上时,后退按钮被用来退出(否则就返回).

处理通知

在桌面平台上, MainLoop 有一个特殊的 MainLoop.NOTIFICATION_WM_QUIT_REQUEST 通知,当请求退出时,会向所有节点发送.

在Android系统中,会发送 MainLoop.NOTIFICATION_WM_GO_BACK_REQUEST 代替.如果在项目设置中勾选了 **Application > Config > Quit On Go Back**(默认),按Back按钮将退出应用程序.

注解

MainLoop.NOTIFICATION_WM_GO_BACK_REQUEST 在iOS上不支持,因为iOS设备没有实体的Back按钮.

处理通知的方法如下(在任何节点上):

GDScript

C#

  1. func _notification(what):
  2. if what == MainLoop.NOTIFICATION_WM_QUIT_REQUEST:
  3. get_tree().quit() # default behavior
  1. public override void _Notification(int what)
  2. {
  3. if (what == MainLoop.NotificationWmQuitRequest)
  4. GetTree().Quit(); // default behavior
  5. }

在开发移动应用程序时,除非用户在主屏幕上,否则不需要退出,因此处理方式有变化.

值得注意的是,默认情况下,在请求退出时,Godot应用程序具有退出的内置行为,可以更改为:

GDScript

C#

  1. get_tree().set_auto_accept_quit(false)
  1. GetTree().SetAutoAcceptQuit(false);

Sending your own quit notification

While forcing the application to close can be done by calling SceneTree.quit, doing so will not send the quit notification. This means the function described above won’t be called. Quitting by calling SceneTree.quit will not allow custom actions to complete (such as saving, confirming the quit, or debugging), even if you try to delay the line that forces the quit.

Instead, you should send a quit request:

GDScript

C#

  1. get_tree().notification(MainLoop.NOTIFICATION_WM_QUIT_REQUEST)
  1. GetTree().Notification(MainLoop.NotificationWmQuitRequest)