ConfirmationDialog in Godot – Complete Guide

Welcome to our tutorial on the ConfirmationDialog class in Godot 4, where we demystify this nifty feature that’s essential for game developers. Creating user interfaces (UI) that communicate effectively with your player is crucial, and ConfirmationDialog is one of those tools that can help you ensure that important decisions are deliberately made within your games. So, buckle up as we unravel the mysteries of ConfirmationDialog, showcasing its practicalities with simplicity and precision.

What Is ConfirmationDialog?

In Godot 4, the ConfirmationDialog is a specialized version of AcceptDialog, designed to confirm user actions. Imagine it as a last checkpoint, a sort of “Are you sure?” moment before a significant action is carried out in your game. This can range from confirming a save file overwrite to accepting the consequences of a character’s choice.

What Is It Used For?

ConfirmationDialogs are handy in situations where you want to avoid accidental clicks or decisions by the player. By providing a clear option to cancel or proceed, it helps ensure that the choice they’re making is intentional and final.

Why Should You Learn It?

Mastering the ConfirmationDialog class is crucial for developers looking to create a polished and professional gaming experience. Not only does it enhance your game’s UX by preventing frustrating mistakes, but it also reflects thoughtful game design, where player choices are respected and consequences are clear. Learning to implement this class effectively can dramatically increase the quality of your user interactions within Godot 4.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Creating a Basic ConfirmationDialog

To begin using a ConfirmationDialog in Godot 4, you first need to add it to your scene. As with any UI element, you want to ensure it’s placed within your scene’s node hierarchy where it makes sense, typically under a canvas or a user interface (UI) node.

var confirm_dialog = ConfirmationDialog.new()
add_child(confirm_dialog)

Once you have the ConfirmationDialog in your scene, you can set its properties. You might want to set the ‘window_title’ property or the ‘dialog_text’ to inform the player exactly what they are confirming:

confirm_dialog.window_title = "Confirm Your Action"
confirm_dialog.dialog_text = "Are you sure you want to perform this action?"

Configuring Buttons

ConfirmationDialog comes with standard ‘Ok’ and ‘Cancel’ buttons by default. Customize the text of these buttons to better fit the context of your game:

confirm_dialog.get_ok().text = "Yes, I'm sure"
confirm_dialog.get_cancel().text = "No, take me back"

You’ll likely need to handle the signals emitted by these buttons to carry out the appropriate actions. You can connect the ‘confirmed’ signal for a positive response and the ‘popup_hide’ signal for a negative one.

confirm_dialog.connect("confirmed", self, "_on_ConfirmDialog_confirmed")
confirm_dialog.connect("popup_hide", self, "_on_ConfirmDialog_cancelled")

func _on_ConfirmDialog_confirmed():
    print("Player has confirmed the action.")

func _on_ConfirmDialog_cancelled():
    print("Player has cancelled the action.")

Show and Hide Dialog

To actually use the dialog within your game, you would typically have it hidden by default and only show it when the player initiates an action that requires confirmation.

confirm_dialog.hide()  # Hide the dialog initially.

# Later in your code, when you need to show the confirmation dialog:
confirm_dialog.popup_centered_ratio(0.5)  # This will show the dialog at a size of 50% of the window

After the player has made their choice, the dialog should be hidden again. This can be handled in your signal methods.

func _on_ConfirmDialog_confirmed():
    print("Player has confirmed the action.")
    confirm_dialog.hide()

func _on_ConfirmDialog_cancelled():
    print("Player has cancelled the action.")
    confirm_dialog.hide()

Now that we have the basic pieces in place, let’s move on to more advanced configurations and usage scenarios.

Advanced Configuration of ConfirmationDialog

For those times when the default look and behavior of the ConfirmationDialog don’t quite match the aesthetic or functional needs of your game, you can delve into more advanced configurations. Customization can include connecting additional signals, styling, and even adding extra UI elements to the dialog.

Let’s look into custom signals. If you have a custom button added to your ConfirmationDialog, you will need to manage its signals:

var custom_button = Button.new()
custom_button.text = "Custom Action"
confirm_dialog.add_child(custom_button)
custom_button.connect("pressed", self, "_on_CustomButton_pressed")

func _on_CustomButton_pressed():
    print("Custom button was pressed.")

In some scenarios, you may want your ConfirmationDialog to include additional information or options, such as checkboxes or input fields:

var checkbox = CheckBox.new()
checkbox.text = "Don't ask me again"
confirm_dialog.add_child(checkbox)

If you want to style your ConfirmationDialog, you can access its theme and style properties. This can greatly enhance the visual integration with the rest of your game:

confirm_dialog.get_ok().add_theme_style_override("font_size", 18)
confirm_dialog.get_cancel().add_theme_style_override("font_color", Color(1, 0, 0))

Modifying the pop-up’s modality can also be a useful feature. By default, the ConfirmationDialog is modal, meaning it will prevent interaction with other UI elements until it is dismissed. However, you can change this behavior:

confirm_dialog.popup_exclusive = false

Another useful configuration is setting a timer to automatically dismiss the dialog after a certain period. This can be especially helpful in giving players a sense of urgency or to avoid stalling the game flow:

var timer = Timer.new()
timer.wait_time = 10.0  # Dialog will close after 10 seconds
timer.one_shot = true
confirm_dialog.add_child(timer)
timer.connect("timeout", confirm_dialog, "hide")
timer.start()

Remember, Godot’s node and signal system is flexible. For instance, you may want to add extra logic when the dialog is shown or hidden, such as pausing the game:

func _on_ConfirmDialog_about_to_show():
    get_tree().paused = true

func _on_ConfirmDialog_hide():
    get_tree().paused = false

confirm_dialog.connect("about_to_show", self, "_on_ConfirmDialog_about_to_show")
confirm_dialog.connect("popup_hide", self, "_on_ConfirmDialog_hide")

These snippets are just the beginning—there’s a wealth of configurations you can explore to make the ConfirmationDialog your own. With careful customizations, the ConfirmationDialog will become an integral part of your game’s UI, guiding your players through critical decisions with ease and style. Don’t forget to test different configurations to find the perfect fit for your game’s design and user experience!

Diving into even more customized behavior, suppose you want to influence the layout within your ConfirmationDialog. Positioning elements such as labels, custom buttons, or even texture items can provide valuable context for the player’s decision.

var label = Label.new()
label.text = "This will affect your character's alignment."
confirm_dialog.get_vbox().add_child(label)  # Adding a label to the ConfirmationDialog's VBoxContainer

Another interesting feature is to respond to keyboard input for an even smoother player experience. For example, you might want to close the dialog when the player presses the ‘Escape’ key:

func _input(event):
    if event.is_action_pressed("ui_cancel"):  # Assuming 'ui_cancel' maps to the 'Escape' key in your project settings.
        confirm_dialog.hide()

You can call input-related functions directly within your ConfirmationDialog’s script, or you could capture them in the main game loop and then call dialog-specific functions.

In scenarios where you want a ConfirmationDialog to have multiple custom buttons, you might opt to create these buttons programmatically and assign unique actions to each:

func create_custom_button(text, action_name):
    var button = Button.new()
    button.text = text
    button.connect("pressed", self, "_on_CustomButton_pressed", [action_name])
    confirm_dialog.add_child(button)

func _on_CustomButton_pressed(action_name):
    print("Button pressed for action: " + action_name)

create_custom_button("Option A", "action_a")
create_custom_button("Option B", "action_b")

Within your ConfirmationDialog, you might also want to include a content area with rich text or media. You can use a RichTextLabel or a TextureRect to accomplish this:

var rich_label = RichTextLabel.new()
rich_label.bbcode_text = "Choosing [b]Yes[/b] will [color=red]permanently[/color] delete data."
confirm_dialog.add_child(rich_label)

# or

var texture_item = TextureRect.new()
texture_item.texture = preload("res://images/warning_icon.png")
confirm_dialog.add_child(texture_item)

The versatility of Godot’s UI nodes allows us to tailor the confirmation dialog to our precise needs. We might even animate its appearance for an attention-grabbing effect:

confirm_dialog.show()
confirm_dialog.rect_scale = Vector2(0, 0)  # Start from no scale
confirm_dialog.tween.interpolate_property(confirm_dialog, "rect_scale",
                                          Vector2(0, 0), Vector2(1, 1), 0.5, Tween.TRANS_BOUNCE, Tween.EASE_OUT)
confirm_dialog.tween.start()

Fine-tuning your ConfirmationDialog to this extent adds depth and refinement to your UI workflows, which greatly contributes to a memorable gameplay experience.

Last but not least, remember to carefully test each unique ConfirmationDialog within the context of its use case. Each dialog should provide a seamless experience, effectively communicate the stakes of the decision being made, and respect the overall aesthetic of your game.

With these tools and techniques at your disposal, the ConfirmationDialog in Godot 4 becomes more than a simple pop-up; it’s transformed into a compelling game element, fully integrated with your game’s narrative and mechanics.

Continuing Your Godot Learning Journey

Embarking on your game development journey with Godot 4 is just the first step towards creating engaging and interactive games. Whether you’ve conquered the ConfirmationDialog class or you’re just getting started, there’s always more to explore and master in this versatile engine. To keep advancing your skills, we encourage you to check out our Godot Game Development Mini-Degree. With a curriculum that covers 2D and 3D game development, GDScript, and various game genres, you’ll be well-equipped to transform your ideas into real-world projects and grow your game development portfolio.

Through high-quality courses at Zenva Academy, learning is both accessible and practical. From beginner lessons to more advanced topics, we offer over 250 courses that can help you evolve from an aspiring developer into a capable creator prepared for opportunities in the gaming market. Along with the Godot Mini-Degree, we also provide a broader range of Godot courses to cater to your every need and interest.

So why wait? Embrace the potential within you and let Zenva be the wind beneath your coding and game development wings. Take charge of your learning experience, earn certificates, and step confidently onto the path to professional game development!

Conclusion

Godot 4’s ConfirmationDialog is a powerful tool, offering an array of possibilities for enhancing player interaction and safeguarding their gameplay experience. Through this guide, you’ve learned how to create, customize, and integrate ConfirmationDialogs into your game, ensuring that your players’ choices are both deliberate and meaningful. As you continue to explore the depths of Godot’s capabilities, remember that this is just a taste of what you can achieve with the right knowledge and skills.

We at Zenva Academy are excited to be part of your journey in game development. Whether you’re looking to fine-tune your expertise in UI elements or dive into the world of gameplay programming, our Godot Game Development Mini-Degree is the perfect next step. Unlock your potential, expand your horizons, and join a community of learners who, like you, are passionate about bringing their gaming visions to life!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.