Up to date
This page is up to date for Godot 4.3.
If you still find outdated information, please open an issue.
處理退出請求
退出
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.
處理通知
在桌面平臺上, MainLoop 有一個特殊的 MainLoop.NOTIFICATION_WM_QUIT_REQUEST 通知, 當請求退出時, 會向所有節點發送.
處理通知的方法如下(在任何節點上):
func _notification(what):
if what == NOTIFICATION_WM_CLOSE_REQUEST:
get_tree().quit() # default behavior
public override void _Notification(int what)
{
if (what == NotificationWMCloseRequest)
GetTree().Quit(); // default behavior
}
值得注意的是, 預設情況下, 在請求退出時,Godot應用程式具有退出的內建行為, 可以更改為:
get_tree().set_auto_accept_quit(false)
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 iOS, you only have approximately 5 seconds to finish a task started by this signal. If you go over this allotment, iOS will kill the app instead of pausing it.
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.
Godot 通知
雖然強迫應用程式關閉可以通過呼叫 SceneTree.quit 來完成,但這樣做不會發送退出的*通知*。這意味著上面描述的函式不會被呼叫。通過呼叫 SceneTree.quit 來退出,將不允許自訂動作的完成(比如保存、確認退出或除錯),即使你試圖延遲強制退出的行。
相反,如果您想通知場景樹中的節點即將到來的程式終止,您應該自己發送通知:
get_tree().root.propagate_notification(NOTIFICATION_WM_CLOSE_REQUEST)
GetTree().Root.PropagateNotification((int)NotificationWMCloseRequest);
發送此通知將通知所有節點有關程式終止的信息,但不會終止程式本身*與 3.X 中不同*。為了實作前面的行為,應該在通知後呼叫 SceneTree.quit <class_SceneTree_method_quit>` 。