Godot Quick Tip #4 - Conditional function execution using ConfirmationDialog and yield
This short scripts helps create a confirmation dialog that can be easily used to execute conditional code.
The script extends from the standard ConfirmationDialog control:
extends ConfirmationDialog var _ctx: GDScriptFunctionState = null func _ready(): get_cancel().connect("pressed", self, "_on_GenericConfirm_canceled") func ask_confirmation(title: String, text: String, ctx: GDScriptFunctionState): window_title = title dialog_text = text _ctx = ctx popup_centered() func _on_GenericConfirm_confirmed(): _ctx.resume(true) func _on_GenericConfirm_canceled(): _ctx.resume(false)
How to use it?
Assuming the node, to which the script is attached, is named GenericConfirm, and is in a Control scene where a Button called Test. You can use the dialog this way:
extends Control func action_to_confirm(): if yield(): print("Action confirmed") else: print("Action canceled") func _on_Test_pressed(): $GenericConfirm.ask_confirmation("Confirm Action", "Do you confirm?", action_to_confirm())
Of course, you can use this dialog in many different scenario.
How does it work?
The trick is all based around the yield function. This function is not easy to understand at first, but basically it allows you to pause the execution of a function and to resume it later.
All starts with the call to the ask_confirmation function. The first two parameters allow to customize the dialog texts. The last parameter is the conditional function. What is important to understand is as soon as yield is called in this function, it stops and returns a state object that will allow us to resume it later. The dialog store this state using the _ctx (short for context) member. Finally, popup_centered is called to display the dialog.
Then the user will either click the OK or the Cancel button. The OK button is handled by _on_GenericConfirm_confirmed, and called the resume function with true as argument. The Cancel button is handled by _on_GenericConfirm_canceled, it works like for OK button use false as argument. What is important to understand here is, as soon as the resume function is called, the conditional function (action_to_confirm in our case) execution will resume at yield, which will return the argument resume receive.
So basically if the user presses the OK button, yield will return true and the function will continue executing whatever is in the if block. If the user presses Cancel, yield will return false and the function will continue executing whatever is in the else block.
Written by Olivier on Monday April 27, 2020