ConfigFile in Godot – Complete Guide

Welcome to our comprehensive tutorial on the ConfigFile class in Godot 4, the versatile and powerful game engine that’s captivated the hearts of indie developers and enthusiasts alike. In this series, we will delve into the intricacies of managing configuration data for your games, an essential skill that can greatly enhance your development workflow. If you’ve ever wondered how to neatly handle game settings, store user preferences, or manage level data, you’re in the right place. Through engaging examples and step-by-step guidance, we promise to unlock the potential of ConfigFile for your projects, making your game development journey both exciting and effective.

What is the ConfigFile Class?

The ConfigFile class is a helper class in Godot that deals with INI-style configuration files. These files are plain text and generally used for storing settings that need to be persistent between game sessions. With its simple structure and ease of use, ConfigFile becomes a powerful tool for managing game configurations, user settings, and even storing data for different levels or environments in your game.

What is ConfigFile Used For?

Imagine you’re creating a game and you want players to customize their experience—things like audio levels, control schemes, or even character names. The ConfigFile class comes in to save the day by providing a way to store and retrieve this information effectively. Since Godot’s approach is flexible and non-restrictive, you can use ConfigFile for:
– **User preferences**: Save and load player preferences.
– **Game settings**: Adjust settings such as difficulty or graphics quality.
– **High scores**: Keep track of player scores in a standardized format.

Why Should I Learn About ConfigFile?

Understanding how to utilize the ConfigFile class in Godot 4 is not just about saving data—it’s about building better, more polished games. Here’s why it’s worth your time:
– **Persistence**: Your game can remember player choices and actions.
– **Flexibility**: Easily change and manage your game’s configurations without muddling with the game’s core code.
– **User Experience**: Provide a more personalized experience for players by remembering their unique settings.

With these concepts in mind, let’s gear up to explore how ConfigFile operates and how you can leverage it to enhance your Godot projects. Whether you’re a beginner learning the ropes or an experienced coder looking to refine your skills, this tutorial series will provide valuable insights into game development with Godot 4.

CTA Small Image

Creating and Saving ConfigFiles

To begin working with ConfigFiles in Godot 4, we need to understand how to create and save them. It’s a straightforward process that resembles working with dictionaries. Let’s dive into the code examples:

var config = ConfigFile()

func save_settings(path):

The code above creates a ConfigFile instance and defines a function to save it. This is our foundational step.

Next, let’s write some settings:

# Assume this is part of a function in a script
config["general"] = {
    "volume": 70,
    "fullscreen": false

# Saving the config file to the user:// directory

We’re populating our ConfigFile with a “general” section containing volume and fullscreen settings, then we’re using our `save_settings` function to save it to a `settings.cfg` file within Godot’s user directory, which is a safe place to store user-specific data.

Loading and Reading ConfigFiles

Now that we’ve saved our settings, we can learn how to load and read them. Below is how we can open and read from an existing config file:

func load_settings(path):
    var error = config.load(path)
    if error == OK:
        print("Settings loaded successfully.")
        print("Failed to load settings.")


The `load_settings` function handles the process, informing us if the loading process was successful or not.

To access the values we’ve loaded:

# Accessing values after loading the settings
var volume = config.get_value("general", "volume", 100)
var fullscreen = config.get_value("general", "fullscreen", true)

print("Volume is set to: ", volume)
print("Fullscreen is: ", fullscreen ? "enabled" : "disabled")

We’re using `config.get_value(section, key, default)` here, which allows us to specify a default value if the key doesn’t exist in the config file.

Handling Sections and Keys

In ConfigFiles, settings are organized into sections and keys, much like a two-dimensional dictionary. Let’s look at how to manipulate these:

# Adding a new section with keys
config["audio"] = {
    "mute": false,
    "music_volume": 40,
    "sfx_volume": 75

# Setting a new key-value pair in an existing section
config.set_value("general", "language", "en")

# Saving the changes

This snippet adds a new “audio” section with keys for muting and volume levels and sets a new key-value pair for language under the “general” section before saving.

Iterating Over ConfigFile Data

Sometimes, we want to inspect what we have in a ConfigFile or display these settings in a GUI. Here’s how to iterate over sections and keys:

# Iterating over all sections
for section in config.get_sections():
    print("Section: ", section)
    # Iterating over all keys in the section
    for key in config.get_section_keys(section):
        var value = config.get_value(section, key)
        print("Key: ", key, ", Value: ", value)

The code outlines a loop through each section, printing out the section name, then each key within that section, along with its corresponding value.

These examples cover the basics of creating, saving, loading, and reading ConfigFiles in Godot 4. In our next segment, we’ll cover more advanced usage and potential pitfalls to look out for. Stay tuned for deeper insights into making the most of ConfigFile’s capability to enrich your game’s functionality and user experience.In the world of game development, advanced usage of the ConfigFile class can open up a realm of possibilities. Let’s explore further capabilities and examples of how ConfigFile can be utilized to create a more dynamic and robust game.

Working with Different Data Types

ConfigFiles in Godot support various data types. You’re not limited to strings and integers; you can also store arrays and dictionaries. Here’s an example of storing more complex data:

# Storing an array
config.set_value("graphics", "resolutions", [1920, 1080])

# Storing a dictionary
config.set_value("player", "attributes", {"speed": 10, "strength": 5})

# Don't forget to save your changes!

These examples add an array of screen resolutions to a “graphics” section and a dictionary of player attributes to a “player” section. Remember that after setting or changing any values, you must save the file to persist the data.

Error Checking During Saving and Loading

Whenever you’re interacting with files, you should be prepared to handle errors. Here’s how you can implement basic error checking when saving and loading ConfigFiles:

func save_settings_with_error_check(path):
    var error =
    if error != OK:
        print("An error occurred while saving the settings.")

func load_settings_with_error_check(path):
    var error = config.load(path)
    if error != OK:
        print("An error occurred while loading the settings.")

These functions build on our earlier examples, adding an error check after the save and load operations and printing an error message if anything goes awry.

Using Custom Resource Paths

ConfigFiles don’t have to be limited to the “user://” directory. You can also save them to custom locations, which can be useful for modding purposes or for saving level-specific configurations:

# Save settings to a custom path

# Load settings from a custom path

These lines of code show how to save and load a ConfigFile to and from a custom directory within the project’s “res://” path, which is typically read-only once exported but useful during development.

Appending and Merging ConfigFile Data

Sometimes, you might want to append new data to an existing ConfigFile without overwriting the current contents. Here’s how you can merge data from one ConfigFile into another:

var default_config = ConfigFile()
var user_config = ConfigFile()

# Load the default config and user config

# Merge user config into default config

# Save the merged ConfigFile"user://settings_merged.cfg")

This snippet demonstrates creating two ConfigFile instances—one for default settings and one for user-specific settings—and merging them together, prioritizing the user settings over the defaults.

Safely Accessing Nested Data

When working with nested data like dictionaries or arrays stored within your ConfigFile, accessing elements safely is crucial to prevent runtime errors. Here’s how you can access nested data safely using the `get_value` method’s default parameter:

# Assume this dictionary is stored under "player" section in the config
# {"name": "Hero", "inventory": {"coins": 100, "potions": 3}}

# Safely access nested dictionary data
var coins = config.get_value("player", "inventory", {}).get("coins", 0)
print("The player has ", coins, " coins.")

If the “inventory” dictionary isn’t present, `get_value` will return an empty dictionary, and the subsequent `get` call will return the default value for “coins”.

These examples should give you a solid foundation for working with ConfigFiles in your Godot projects. From here, you can start experimenting with ConfigFile’s versatility in your game, whether it be for saving game progress, managing user profiles, or streamlining game settings. Happy coding!As we delve deeper into the advanced usage of the `ConfigFile` class in Godot 4, let’s explore some practical scenarios you might encounter while developing your game.

Conditional Loading of ConfigFiles

Consider a situation where you want to load user settings if they exist, but fall back on default settings if not. Here’s how you can do that:

func load_or_create_settings(path, default_path):
    var error = config.load(path)
    if error != OK:
        print("User settings not found. Loading default settings.")

# Usage
load_or_create_settings("user://user_settings.cfg", "res://default_settings.cfg")

This function attempts to load the user settings and, if unsuccessful, loads the default settings instead.

Incrementally Updating ConfigFile Data

Updating existing data might be necessary, for example, when a player earns more coins. Here’s how to incrementally update a value:

func add_coins(amount):
    var current_coins = config.get_value("player", "coins", 0)
    config.set_value("player", "coins", current_coins + amount)

# Add 50 coins to the player's total

This function retrieves the current coin count, adds the specified amount, and updates the `ConfigFile`.

Sanitizing Data Before Saving

It’s important to ensure that the data being saved into a `ConfigFile` is valid and in a format you expect. Here’s a quick example of validating data before saving:

func save_player_name(new_name):
    if new_name.is_valid_identifier():
        config.set_value("player", "name", new_name.trim())
        print("Invalid player name.")

# Try saving a new player name
save_player_name(" Gamer123 ")

The function checks whether the new name is a valid identifier and trims any whitespace before saving the name to the `ConfigFile`.

Encrypting ConfigFiles for Added Security

For sensitive data, Godot allows you to encrypt your `ConfigFile`. Here’s an example using an encryption key:

var key = "supersecretkey"

func save_encrypted_settings(path):
    var file =
    var data = config.save_encrypted_with_pass_to_buffer(key)
    if file.open_encrypted_with_pass(path, File.WRITE, key) == OK:
        print("Settings saved securely.")
        print("Failed to save settings securely.")

# Use this method to save settings with encryption

This snippet uses a passphrase to encrypt the `ConfigFile` contents before saving it to the disk.

Creating a Settings Manager

Often, you’ll want a central class to handle all your game’s settings. Here’s a simplified version of a settings manager:

class SettingsManager:
    var config = ConfigFile()
    var settings_path = "user://settings.cfg"

    func _init():

    func load_settings(path):

    func get_setting(section, key, default_value):
        return config.get_value(section, key, default_value)

    func set_setting(section, key, value):
        config.set_value(section, key, value)

    func save_settings():

# Instance of SettingsManager in your game
var settings_manager =

Here we create a `SettingsManager` class that encapsulates the logic of loading, getting, setting, and saving settings in a `ConfigFile`.

With these examples and concepts, you are now equipped with a robust set of tools to manage configuration files within your Godot games. Using `ConfigFile` class effectively can significantly boost the professionalism and user-friendliness of your game by providing a tailored experience that persists across sessions. Experiment with these advanced techniques and integrate them into your game development workflow for smoother and more efficient processes.

Continuing Your Game Development Journey

Embarking on your game development journey with Godot is an exciting endeavor, and mastering the `ConfigFile` class is just the beginning. To take your skills even further and truly harness the power of Godot, we invite you to explore our Godot Game Development Mini-Degree. This comprehensive program will guide you through creating cross-platform games and mastering the foundational to advanced concepts necessary for a professional portfolio.

Our curriculum is designed to accommodate learners at various stages, whether you’re just starting out or looking to deepen your existing expertise. By diving into the robust world of 2D and 3D game development with Godot, you’ll gain practical experience and in-demand skills that will open doors to opportunities in the game industry.

And, if you’re interested in broadening your Godot knowledge base, be sure to check out our diverse collection of Godot courses. At Zenva, we are committed to helping you progress from beginner to professional with clarity and confidence. Continue your learning journey with us, and let’s bring your game development aspirations to life!


As we wrap up our exploration of Godot’s `ConfigFile` class, we hope you feel empowered to save, load, and manage data with finesse in your own games. Remember, understanding how to use tools like `ConfigFile` effectively is what can distinguish a good game from a great one. It’s the attention to detail in your development process that contributes to a seamless and enjoyable player experience.

Continue to hone your development skills with our Godot Game Development Mini-Degree and become the game developer you’ve always wanted to be. Embrace the challenges and joys of game creation, and let Zenva be your guide every pixel of the way. Keep coding, keep creating, and let’s transform your visions into playable realities!

Python Blog Image

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