Files
whale-town/scripts/ChineseFontLoader.gd
2025-12-06 17:33:14 +08:00

50 lines
1.4 KiB
GDScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
extends Node
## 中文字体加载器
## 自动为所有 Label 和 RichTextLabel 应用中文字体
# 字体文件路径(根据你的实际路径修改)
const FONT_PATHS = [
"res://assets/fonts/msyh.ttc",
"res://assets/fonts/simhei.ttf",
"res://assets/fonts/simsun.ttc",
]
var chinese_font: Font = null
func _ready():
# 加载字体
load_chinese_font()
# 应用到所有现有节点
if chinese_font:
apply_font_to_all_labels(get_tree().root)
print("中文字体已应用到所有 Label 节点")
else:
push_warning("未找到中文字体文件,请检查 assets/fonts/ 目录")
func load_chinese_font():
# 尝试加载字体文件
for font_path in FONT_PATHS:
if FileAccess.file_exists(font_path):
chinese_font = load(font_path)
if chinese_font:
print("成功加载中文字体: " + font_path)
return
# 如果没有找到字体文件,尝试创建一个带回退的字体
push_warning("未找到预设的中文字体文件")
func apply_font_to_all_labels(node: Node):
# 如果是 Label 或 RichTextLabel应用字体
if node is Label or node is RichTextLabel:
node.add_theme_font_override("font", chinese_font)
# 递归处理所有子节点
for child in node.get_children():
apply_font_to_all_labels(child)
# 公共方法:为新创建的节点应用字体
func apply_font_to_node(node: Node):
if chinese_font and (node is Label or node is RichTextLabel):
node.add_theme_font_override("font", chinese_font)