EditorTranslationParserPlugin in Godot – Complete Guide

Localization and translation are crucial aspects of game development, pivotal to reaching a wider audience and ensuring your game is inclusive and accessible. Imagine creating an immersive game world where players from various cultural backgrounds can experience your story in their native tongue. This is where tools like the EditorTranslationParserPlugin in Godot 4 come into the picture, making the translation process seamless and efficient.

What is EditorTranslationParserPlugin?

The EditorTranslationParserPlugin is an extendable class within the Godot 4 engine designed to hook custom parsers for extracting localizable strings from various file types, such as .csv or .json files. By overriding the _parse_file method, developers can define custom logic to locate and export these strings into a POT (Portable Object Template) file, which is used to manage and organize translations in numerous languages.

What is it for?

The primary purpose of the EditorTranslationParserPlugin is to provide a customizable way to parse and extract text from project files that are to be translated. This allows developers to support various data structures and file formats, depending on the needs of their specific project, ensuring that all translatable content can be easily found and managed.

Why Should I Learn It?

Learning to use the EditorTranslationParserPlugin broadens your Godot game development toolkit by enabling you to create games that are ready for a global audience. It’s not only about the technical aspects of string extraction but also about the ability to gracefully adapt content for players from different linguistic backgrounds. By incorporating this into your workflow, you ensure that your game can communicate with players universally, which is a mark of professional and considerate game design.

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

Setting Up the EditorTranslationParserPlugin

Let’s dive into setting up the EditorTranslationParserPlugin in Godot 4. The first step is to create a new plugin within Godot that will host our custom parser.

tool
extends EditorPlugin

var parser = preload("res://path_to_your_parser.gd")

func _enter_tree():
    add_translation_parser_plugin(parser.new())

In the example above, we’ve defined a new EditorPlugin script that preloads our custom parser script and adds a new instance of it to the translation parser plugins when the plugin is enabled.

Creating Our Custom Translation Parser

Now, we create our custom parser by extending the EditorTranslationParserPlugin class. Override the `_parse_file()` method to define how to extract localizable strings from your files.

extends EditorTranslationParserPlugin

func _parse_file(path, extracted_strings):
    var file = File.new()
    if file.open(path, File.READ) != OK:
        return ERR_CANT_OPEN

    while not file.eof_reached():
        var line = file.get_line()
        # Assuming a simple key="value" format
        var match = line.match('(\w+)="(.*)"')
        if match:
            var key = match[1]
            var text = match[2]
            extracted_strings.append(text)
    file.close()
    return OK

The example parser above assumes you have a file with lines like `key=”Localizable text”`. It opens the file, reads each line, and uses regular expressions to find matches and extract the strings.

Registering File Types for Custom Parsing

Custom parsers are most useful when you have non-standard file types that contain localizable strings. Here’s how you can register your parser to handle custom file extensions:

func _enter_tree():
    add_translation_parser_plugin(parser.new())
    EditorTranslationParserPlugin.add_parser_supported_extension("custom")

func _exit_tree():
    EditorTranslationParserPlugin.remove_parser_supported_extension("custom")

These code snippets should be included in your EditorPlugin script. They register “.custom” file extension with the translation parsing system when the plugin is enabled and unregister it when the plugin is disabled.

Extracting Localizable Strings from JSON Files

JSON files often store localizable strings, especially in data-driven games. Custom parsers can efficiently handle JSON structures:

extends EditorTranslationParserPlugin

func _parse_file(path, extracted_strings):
    var file = File.new()
    if file.open(path, File.READ) != OK:
        return ERR_CANT_OPEN

    var json = parse_json(file.get_as_text())
    file.close()
    _extract_strings_from_json(json, extracted_strings)
    return OK

func _extract_strings_from_json(json, extracted_strings):
    # Recursive function to handle nested dictionaries and arrays
    if typeof(json) == TYPE_DICTIONARY:
        for key in json.keys():
            _extract_strings_from_json(json[key], extracted_strings)
    elif typeof(json) == TYPE_ARRAY:
        for item in json:
            _extract_strings_from_json(item, extracted_strings)
    elif typeof(json) == TYPE_STRING:
        extracted_strings.append(json)

In this example, the parser opens a JSON file, parses it, and recursively searches for strings, taking into account the hierarchical nature of JSON data.

By now, you should have a functional understanding of how to set up and use the EditorTranslationParserPlugin to prepare your game’s text for localization. Next, we’ll cover how to export these strings into a POT file and integrate translations back into Godot 4. Stay tuned for more practical examples that will bring your game closer to a global audience!Great, we’ll move on to exporting the strings we’ve extracted and how to integrate translations back into the Godot 4 engine.

Exporting Extracted Strings to a POT File

Once you have your strings extracted using the custom parser, the next step is to export them into a POT file for translation. To do this, you can use the EditorTranslationExportPlugin:

tool
extends EditorTranslationExportPlugin

func _export_translations(path, extracted_strings, options):
    var file = File.new()
    if file.open(path, File.WRITE) != OK:
        push_error("Failed to open file for writing: " + path)
        return

    for text in extracted_strings:
        file.store_line('msgid "%s"' % text)
        file.store_line('msgstr ""')
        file.store_line("")  # Add an empty line for readability

    file.close()

This exemplifies how to create a simple POT file that translators can use to provide the corresponding translations.

Adding Locale and Importing Translations

To integrate translations back into your Godot project, create a .po file for each language you’re translating into and then add the locale in the project settings.

Adding a new locale:

ProjectSettings.set_setting("locale/translations", PoolStringArray(["res://translations/spanish.po"]))

This code snippet adds a Spanish translation file to the project settings.

Using Translations In-Game

Once your translations are in place, use the TranslationServer to translate your text in-game:

var spanish = TranslationServer.get_translation("res://translations/spanish.po")
TranslationServer.add_translation(spanish)
TranslationServer.set_locale("es") # Set the locale to Spanish

This snippet loads the Spanish translation file, adds the translation to the TranslationServer, and sets the current locale to Spanish.

Translating UI Elements

UI elements in Godot can be translated on-the-fly using the `tr()` function, which looks for a matching translation key in the current locale’s .po file:

In a Label node script:

func _ready():
    text = tr("Hello World")  # 'Hello World' being a key in your .po file

The `text` of the Label will display the translated string according to the current language set.

Switching Languages Dynamically

Allow players to switch languages dynamically during gameplay:

func switch_language(locale):
    TranslationServer.set_locale(locale)
    # You need to update all visible text to reflect the change
    update_visible_texts()

func update_visible_texts():
    # This function finds all nodes that need text updates and changes them
    for label in get_tree().get_nodes_in_group("localizable"):
        label.text = tr(label.text)

This approach requires updating all on-screen text whenever the language is switched. The ‘localizable’ group is assumed to contain all UI elements that display text.

By following these steps, you’ve engaged in the full cycle of localizing your Godot game, from extracting strings to displaying translations in-game. Understanding and implementing this process puts you one step closer to making your game accessible to a wider audience, breaking language barriers and enriching the gaming experience for players around the globe. With these tools and knowledge, we at Zenva are excited to see you create games that resonate across cultures and communities.Localization is more than translating text; it also involves adapting game content to different cultural contexts. Let’s explore some advanced features and tips to make your game localization-ready with Godot 4.

When localizing UI elements that include numbers, dates, or currency, proper formatting according to the locale is crucial. Here’s how you can handle localization for such elements.

Formatting Numbers and Currency

Godot’s built-in localization tools can handle numeric localization with the proper integration:

var number_to_display = 12345.67
# Format the number based on the current locale
var formatted_number = TranslationServer.format_number(number_to_display)

# If you want to format it as currency
var formatted_currency = TranslationServer.format_currency(number_to_display)

These methods automatically format numbers and currency according to the active locale’s conventions.

Date and Time Localization

Dates and times also need localization as different regions have different formats:

var date_to_display = OS.get_date()
var time_to_display = OS.get_time()

# Format the date and time based on the current locale
var formatted_date = TranslationServer.format_date(date_to_display)
var formatted_time = TranslationServer.format_time(time_to_display)

This ensures that your in-game calendars and clocks are culturally accurate.

Detecting the Player’s Locale

Godot can detect the player’s system locale, offering a starting point for setting the game’s default language:

var locale = OS.get_locale()

func _ready():
    if locale.begins_with("es"):
        TranslationServer.set_locale("es")
    elif locale.begins_with("fr"):
        TranslationServer.set_locale("fr")
    # Add other languages here as needed

Setting the locale based on the player’s system settings makes the game feel more personalized.

Localization for Audio Files

Localization can extend to audio files for voice-over or instructions. Here’s a simple way to dynamically load audio clips based on the current locale:

var voice_clip = load("res://audio/voiceover_" + TranslationServer.get_locale() + ".ogg")

func _ready():
    var audio_player = $AudioPlayer
    audio_player.stream = voice_clip
    audio_player.play()

You can organize and name your audio files using the locale code to streamline the process.

Localization is not just about words; it’s about providing a familiar and comfortable experience for all players. Godot’s localization features, including the EditorTranslationParserPlugin, pave the way for your game to offer this seamlessly. With these tools and code examples, you are well-equipped to take your game global, engaging players from various linguistic and cultural backgrounds.

Creating an inclusive gaming environment is key to broadening your game’s appeal, and we at Zenva are dedicated to helping you achieve that. Through careful localization, your game can become an inviting and captivating experience for players around the world.

Continuing Your Game Development Journey with Godot

Your adventure into game development has just begun, and the skills you’ve acquired are solid stepping stones towards creating engaging and globally accessible games. To keep the momentum and further enrich your game development toolkit, consider elevating your expertise with our comprehensive Godot Game Development Mini-Degree. This curated program is tailored to blend seamlessly into your learning path, offering a diverse range of projects and practical know-how.

Dive into seven dynamic courses that cover essentials from crafting 2D and 3D games, mastering game mechanics, to adding polished UI systems. This mini-degree is crafted for aspiring developers of all levels, ensuring that you can jump in and start crafting your first game in no time. The flexible online format, coding challenges, and quizzes hosted by Zenva Academy enhance your learning experience, empowering you to succeed in the creative realm of game development.

But why stop there? Explore our vast collection of Godot courses to discover a world of opportunities in game creation. Whether you’ve just started or are looking to sharpen your skills, Zenva’s range of courses offers a valuable asset for learners eager to turn their visions into playable realities. Embrace the journey, and let’s build unforgettable gaming experiences together!

Conclusion

Embarking on the path of game development is an adventure filled with creativity, challenges, and excitement. As you harness the power of Godot 4 and tools like the EditorTranslationParserPlugin, remember that each step you take enhances your ability to tell stories and create experiences that resonate worldwide. Localizing your game is more than a technical task; it’s a bridge between cultures, an invitation to players across the globe to immerse themselves in the world you’ve created.

Keep pushing forward and expanding your understanding of game development with our Godot Game Development Mini-Degree, a resource designed to help you grow from novice to expert at your own pace. So go ahead, take what you’ve learned, and let your passion for game creation reach every corner of the Earth. Together, we’ll continue to redefine the boundaries of interactive entertainment.

FREE COURSES
Python Blog Image

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