处理退出请求

退出

Most platforms have the option to request the application to quit. On desktops, this is usually done with the “x” icon on the window title bar. On mobile devices, the app can quit at any time while it is suspended to the background.

处理通知

在桌面及 Web 平台上, Node 会在窗口管理器发出退出请求时接受到 MainLoop.NOTIFICATION_WM_QUIT_REQUEST 通知.

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

GDScriptC#

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

It is important to note that by default, Godot apps have the built-in behavior to quit when quit is requested from the window manager. This can be changed, so that the user can take care of the complete quitting procedure:

GDScriptC#

  1. get_tree().set_auto_accept_quit(false)
  1. GetTree().AutoAcceptQuit = false;

On mobile devices

There is no direct equivalent to NOTIFICATION_WM_CLOSE_REQUEST on mobile platforms. Due to the nature of mobile operating systems, the only place that you can run code prior to quitting is when the app is being suspended to the background. On both Android and iOS, the app can be killed while suspended at any time by either the user or the OS. A way to plan ahead for this possibility is to utilize NOTIFICATION_APPLICATION_PAUSED in order to perform any needed actions as the app is being suspended.

On Android, pressing the Back button will exit the application if Application > Config > Quit On Go Back is checked in the Project Settings (which is the default). This will fire NOTIFICATION_WM_GO_BACK_REQUEST.

发送你自己的退出通知

虽然可以通过调用 SceneTree.quit 来强制关闭应用程序,但这样做不会向节点及场景树发送 NOTIFICATION_WM_CLOSE_REQUEST。通过调用 SceneTree.quit 来退出程序会导致自定义动作无法完成(比如保存、确认退出或调试),即使你试图延后执行强制退出的那行代码。

作为替代,如果你想通知节点以及场景树应用程序即将终止,你应当自己发送对应的通知:

GDScriptC#

  1. get_tree().root.propagate_notification(NOTIFICATION_WM_CLOSE_REQUEST)
  1. GetTree().Root.PropagateNotification((int)NotificationWMCloseRequest);

如此做将会通知所有的节点应用程序即将终止,但是不会关闭应用程序本身 (与3.X版本不同) 。如果需要达到之前的效果,则应当在发送通知后调用 SceneTree.quit