
Godot 游戏本地化完整指南
从 TranslationServer 到字体回退:使用 CSV、PO 文件、GDScript 和自动化 AI 翻译本地化 Godot 游戏。
TranslationServer 基础
Godot 内置的 TranslationServer 是本地化系统的核心。它在启动时加载翻译资源,并通过 tr() 函数解析键。GDScript 对 tr() 的每次调用都会经过 TranslationServer,无需额外的库。
# TranslationServer is Godot's built-in localization system.
# It loads translations at startup and resolves keys via tr().
# Set the game's locale
TranslationServer.set_locale("ja")
# Get the current locale
var current = TranslationServer.get_locale() # "ja"
# Translate a key — works everywhere in GDScript
var text = tr("MENU_START") # "ゲームスタート"
# Translate with context (Godot 4.x)
var text = tr("OPEN", "verb") # "Open" (action)
var text = tr("OPEN", "adj") # "Open" (state)CSV 翻译文件
CSV 是 Godot 翻译最简单的格式。一个文件按列保存所有语言。第一列是键,之后每列是一种区域设置。Godot 会自动导入 .csv 文件并生成 .translation 资源。
# translations.csv
# First column = key, subsequent columns = locale codes
keys,en,ja,de,es
MENU_START,Start Game,ゲームスタート,Spiel starten,Iniciar juego
MENU_SETTINGS,Settings,設定,Einstellungen,Configuración
MENU_QUIT,Quit,終了,Beenden,Salir
ITEM_SWORD,Sword,剣,Schwert,Espada
ITEM_SHIELD,Shield,盾,Schild,Escudo
DIALOG_GREETING,"Hello, adventurer!",冒険者よ、こんにちは!,"Hallo, Abenteurer!","¡Hola, aventurero!"# In Godot Editor:
# 1. Place your .csv file in the project (e.g., res://translations.csv)
# 2. Godot auto-imports it — creates .translation resources
# 3. Go to Project > Project Settings > Localization > Translations
# 4. Add the generated .translation filesPO/Gettext 翻译文件
PO(Portable Object)文件是软件本地化的行业标准。Godot 4.x 原生支持 PO,包括复数、上下文消歧和译者注释。在 locale/ 目录中为每种语言创建一个 .po 文件。
# translations.po — Gettext format for Godot
# Place in res://locale/ja.po
msgid ""
msgstr ""
"Language: ja\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=1; plural=0;\n"
# Simple translation
msgid "MENU_START"
msgstr "ゲームスタート"
# Translation with context (disambiguates identical source strings)
msgctxt "verb"
msgid "OPEN"
msgstr "開く"
msgctxt "adj"
msgid "OPEN"
msgstr "開いている"
# Plural form
msgid "You collected %d coin."
msgid_plural "You collected %d coins."
msgstr[0] "%d枚のコインを集めました。"# Project Settings > Localization > Translations
# Add each .po file:
# res://locale/en.po
# res://locale/ja.po
# res://locale/de.po
# res://locale/es.po
# Or load programmatically:
func _ready():
var translation = load("res://locale/ja.po")
TranslationServer.add_translation(translation)在 GDScript 中使用翻译
在 GDScript 的任意位置使用 tr() 翻译字符串。结合 GDScript 的 % 运算符进行字符串格式化。为稳健地管理区域设置,可创建一个 Autoload 脚本,通过信号处理区域设置检测、持久化和切换。
extends Control
func _ready():
# Simple key lookup
$TitleLabel.text = tr("MENU_START")
# With string formatting (positional)
$GreetingLabel.text = tr("DIALOG_GREETING_NAME") % [player_name]
# With multiple placeholders
$StatusLabel.text = tr("PLAYER_STATUS") % [player_name, level, health]
# Context-aware translation (Godot 4.x)
$ActionButton.text = tr("OPEN", "verb")
# Update UI when locale changes
TranslationServer.set_locale("de")
_update_ui()
func _update_ui():
# Re-apply all translated strings
$TitleLabel.text = tr("MENU_START")
$GreetingLabel.text = tr("DIALOG_GREETING_NAME") % [player_name]# locale_manager.gd — Register as Autoload in Project Settings
extends Node
signal locale_changed(new_locale: String)
const SUPPORTED_LOCALES = ["en", "ja", "de", "es", "fr", "ko", "zh"]
func _ready():
var system_locale = OS.get_locale_language()
if system_locale in SUPPORTED_LOCALES:
set_locale(system_locale)
else:
set_locale("en")
func set_locale(locale: String):
TranslationServer.set_locale(locale)
locale_changed.emit(locale)
func get_locale() -> String:
return TranslationServer.get_locale()复数和占位符
Godot 通过 PO 文件的复数形式处理复数。每种语言都在 PO 标头中定义自己的复数公式。GDScript 的 % 运算符处理位置占位符(%s 用于字符串,%d 用于整数)。对于命名占位符,请使用 String.replace()。
# Godot uses Gettext PO plural rules.
# Each language defines its own plural formula.
# English (2 forms: one, other)
msgid "You collected %d coin."
msgid_plural "You collected %d coins."
msgstr[0] "You collected %d coin."
msgstr[1] "You collected %d coins."
# Japanese (1 form: other — no singular/plural distinction)
msgid "You collected %d coin."
msgid_plural "You collected %d coins."
msgstr[0] "%d枚のコインを集めました。"
# Russian (3 forms: one, few, many)
msgid "You collected %d coin."
msgid_plural "You collected %d coins."
msgstr[0] "Вы собрали %d монету."
msgstr[1] "Вы собрали %d монеты."
msgstr[2] "Вы собрали %d монет."# GDScript string formatting with tr()
# Positional placeholders with %
var msg = tr("SCORE_MSG") % [score] # "Score: %d" → "Score: 1500"
var msg = tr("STATS") % [name, level, hp] # "%s — Lv %d — HP: %d"
# Named placeholders (manual replacement)
var template = tr("WELCOME_BACK")
var msg = template.replace("{player}", name).replace("{days}", str(days))CJK、阿拉伯文等文字的字体回退
游戏的主要字体很可能不包含日文、韩文、中文、阿拉伯文或泰文字符。Godot 4.x 支持字体回退链:主要字体缺少某个字形时,Godot 会按顺序检查回退字体。若未设置,非拉丁文字会呈现为空方框。
# Godot 4.x supports font fallback chains.
# When a glyph is missing from the primary font, fallbacks are checked in order.
# In the Editor:
# 1. Create a LabelSettings or Theme resource
# 2. Set the primary font (e.g., Noto Sans for Latin)
# 3. Add fallback fonts: Noto Sans JP, KR, SC, Arabic
# Programmatically:
func setup_fonts():
var font = FontFile.new()
font.load_dynamic_font("res://fonts/NotoSans-Regular.ttf")
var fallback_jp = FontFile.new()
fallback_jp.load_dynamic_font("res://fonts/NotoSansJP-Regular.ttf")
font.add_fallback(fallback_jp)
$Label.add_theme_font_override("font", font)# Right-to-left (RTL) support for Arabic, Hebrew, etc.
# In the Editor:
# Select your Control node > Layout > Text Direction = RTL
# Programmatically:
func setup_rtl():
var locale = TranslationServer.get_locale()
var rtl_locales = ["ar", "he", "fa", "ur"]
if locale.substr(0, 2) in rtl_locales:
$Label.text_direction = Control.TEXT_DIRECTION_RTL
$Container.layout_direction = Control.LAYOUT_DIRECTION_RTL场景和 UI 本地化
本地化 Godot 场景有三种方法:在 _ready() 中使用 tr() 翻译;使用编辑器中的 Auto Translate 属性;或为需要不同布局的语言(例如 RTL 语言)加载完全不同的场景。
# Approach 1: Translate in _ready() using tr()
extends Control
func _ready():
$StartButton.text = tr("MENU_START")
$SettingsButton.text = tr("MENU_SETTINGS")
$QuitButton.text = tr("MENU_QUIT")
# Approach 2: Use auto-translate in the editor
# Set the Text property to the translation key (e.g., "MENU_START")
# and enable "Auto Translate" on the node.
# Approach 3: Locale-specific scenes for complex layouts
func load_localized_scene():
var locale = TranslationServer.get_locale().substr(0, 2)
var path = "res://ui/main_menu_%s.tscn" % locale
if ResourceLoader.exists(path):
add_child(load(path).instantiate())
else:
add_child(load("res://ui/main_menu_en.tscn").instantiate())使用 LocaleChain 实现智能区域设置回退
地区变体缺失时,Godot 的 TranslationServer 会直接回退到项目的默认区域设置。如果只有 pt-PT 翻译,pt-BR 玩家会看到英语而非葡萄牙语。LocaleChain 在配置时将可配置回退链中的翻译合并到 TranslationServer,解决此问题。
# LocaleChain for Godot — smart locale fallback
# Install from Godot AssetLib or copy addons/locale_chain/ into your project
# Problem: Godot's TranslationServer falls back directly to the default locale.
# A pt-BR player with only pt-PT translations sees English, not Portuguese.
# Solution: One-line setup
func _ready():
LocaleChain.configure() # Uses built-in fallback chains
# Now pt-BR falls back to pt-PT → pt → default
# es-MX falls back to es-419 → es → default
# zh-Hant-HK falls back to zh-Hant-TW → zh-Hant → default
# Custom configuration:
func _ready():
# Override specific chains
LocaleChain.configure({"pt-BR": ["pt"]})
# Full custom — only your chains
LocaleChain.configure(
{"pt-BR": ["pt-PT", "pt"], "es-MX": ["es-419", "es"]},
false # don't merge defaults
)
# Reset to original state
LocaleChain.reset()自动翻译游戏
完成本地化设置后,使用 AI 翻译 CSV 或 PO 文件。直接从 IDE 或 CI/CD 管线自动翻译游戏字符串、UI 文本、物品说明和对话。
# Translate your Godot locale files with AI
# CSV files:
# In your IDE, ask your AI assistant:
> Translate translations.csv to Japanese, Korean, and German
# PO files:
> Translate locale/en.po to ja, ko, de
# Or use the CLI in CI/CD:
npx i18n-agent translate locale/en.po --lang ja,ko,de
# The tool preserves:
# - CSV column structure and delimiters
# - PO msgctxt, msgid_plural, and plural forms
# - Placeholder syntax (%s, %d, {name})
# - Comments and metadata headers自动保证翻译质量
常见问题
未导入翻译文件
包含逗号或引号的 CSV 值导致解析失败
CJK 或阿拉伯文显示为空方框
PO 标头中的复数形式数量不正确
自动翻译被代码覆盖
推荐的项目结构
my_godot_game/
├── addons/
│ └── locale_chain/ # LocaleChain plugin (optional)
│ ├── fallback_map.gd
│ ├── locale_chain.gd
│ └── plugin.cfg
├── fonts/
│ ├── NotoSans-Regular.ttf # Primary font (Latin)
│ ├── NotoSansJP-Regular.ttf # Japanese fallback
│ ├── NotoSansKR-Regular.ttf # Korean fallback
│ └── NotoSansArabic-Regular.ttf # Arabic fallback
├── locale/
│ ├── en.po # English (source)
│ ├── ja.po # Japanese
│ ├── de.po # German
│ ├── es.po # Spanish
│ └── ar.po # Arabic
├── translations.csv # Alternative: CSV format
├── scenes/
│ └── ui/
│ ├── main_menu.tscn
│ └── settings_menu.tscn
├── scripts/
│ ├── locale_manager.gd # Autoload for locale management
│ └── ui/
│ └── main_menu.gd
├── project.godot
└── export_presets.cfg立即试用 i18n Agent
将翻译文件拖放到此处
JSON, YAML, PO, XML, CSV, Markdown, Properties
或点击选择文件
目标语言
使用 locale-chain-godot 实现区域设置回退
当 pl_PL 等地区区域设置缺少翻译键时,Godot 会直接跳到项目的默认区域设置,而不会先检查父级区域设置 pl。
# Install from Godot Asset Library
# Search: locale-chain-godotvar lc = LocaleChain.new()
lc.configure({
"pl": ["pl_PL", "en"],
"pt_BR": ["pt", "en"],
"zh_Hant_HK": ["zh_Hant", "zh", "en"],
})查看语言回退指南,了解受支持框架的完整列表和 75 条内置回退链。 Learn more →