How do I translate text by code?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Calinou
:warning: Old Version Published before Godot 3 was released.

I know I can set a button’s text to a translation key, and it gets automatically translated this way. But what if I set the text by code using GDScript?

:bust_in_silhouette: Reply From: Calinou

Use the tr(text) method, like this:

func _ready():

This will automatically look up the key HELLO when the project starts, and translate it to the user’s language (if found in the localization table).

If you need to perform replacements in the translated text, you can do something like this:

func _ready():
    print(tr("HELLO_NAME").replace("%1", player_name))

For this to work, your translation text will have to contain a text that matches the %1. Note that %1 is just an example, you could use anything instead, it should probably be unique in each string though.