godot-gdscript
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGodot GDScript (4.x)
Godot GDScript (4.x)
Write correct, statically typed GDScript and use the node lifecycle and signal
system the way the engine intends. Targets Godot 4.3+ (GDScript 2.0).
编写符合引擎设计规范的静态类型GDScript,正确使用节点生命周期与信号系统。目标版本为Godot 4.3+(GDScript 2.0)。
When to use
使用场景
- Use when writing or fixing files: declaring variables, functions, classes, using
.gd/@export, connecting signals, or awaiting coroutines/signals.@onready - Use when porting Godot 3.x scripts to 4.x and the script no longer parses.
When not to use: scene/node structure and instancing questions →
; signal architecture/decoupling patterns →
; using C# instead of GDScript → .
godot-nodes-scenesgodot-signals-groupsgodot-csharp- 编写或修复文件时使用:声明变量、函数、类,使用
.gd/@export,连接信号,或是等待协程/信号。@onready - 将Godot 3.x脚本移植到4.x版本且脚本无法解析时使用。
请勿用于以下场景:场景/节点结构与实例化相关问题 → 请使用;信号架构/解耦模式相关问题 → 请使用;使用C#而非GDScript开发 → 请使用。
godot-nodes-scenesgodot-signals-groupsgodot-csharpCore workflow
核心工作流
- Type everything you can. GDScript 2.0 supports static types
(,
var hp: int = 10). Types catch errors at parse time and speed up the VM. Usefunc add(a: int, b: int) -> int:for inferred types.:= - Use the lifecycle callbacks for their purpose: once when the node and its children enter the tree;
_ready()every rendered frame;_process(delta)on the fixed physics tick (use it for movement/physics)._physics_process(delta) - Grab node references with , not in
@onready— children do not exist until the node enters the tree._init() - Expose tunables with so designers edit them in the Inspector.
@export - React to events with signals + , not polling, where it reads cleanly.
await - Run and read errors. The Debugger panel prints typed errors with line numbers; fix the first error first (later ones are often cascades).
- 尽可能为所有内容添加类型。GDScript 2.0支持静态类型(如、
var hp: int = 10)。类型检查可在解析阶段捕获错误,还能提升虚拟机运行速度。使用func add(a: int, b: int) -> int:进行类型推断。:= - 按用途使用生命周期回调函数:在节点及其子节点加入场景树时执行一次;
_ready()在每一渲染帧执行;_process(delta)在固定物理帧执行(用于移动/物理相关逻辑)。_physics_process(delta) - 使用获取节点引用,不要在
@onready中获取——子节点在节点加入场景树前并不存在。_init() - 使用暴露可调节参数,方便设计师在检查器中编辑。
@export - 使用信号 + 响应事件,在代码可读性良好的情况下,避免使用轮询方式。
await - 运行脚本并查看错误信息。调试器面板会显示带行号的类型错误;优先修复第一个错误(后续错误通常是连锁反应导致)。
Patterns
模式示例
1. A typed script with lifecycle, @export, and @onready
1. 包含生命周期、@export与@onready的类型化脚本
gdscript
extends Node2D
class_name Spinner # registers a global type usable in other scripts
@export var speed: float = 90.0 # editable in the Inspector (degrees/sec)
@export_range(0, 10, 0.5) var wobble := 2.0
@onready var sprite: Sprite2D = $Sprite2D # resolved when the node enters the tree
func _ready() -> void:
# Runs once, after children are ready. Safe to touch $Sprite2D here.
sprite.modulate = Color.AQUA
func _process(delta: float) -> void:
# delta is seconds since last frame; multiply rates by it for FPS independence.
rotation_degrees += speed * deltagdscript
extends Node2D
class_name Spinner # 注册全局类型,可在其他脚本中使用
@export var speed: float = 90.0 # 可在检查器中编辑(单位:度/秒)
@export_range(0, 10, 0.5) var wobble := 2.0
@onready var sprite: Sprite2D = $Sprite2D # 节点加入场景树时解析引用
func _ready() -> void:
# 仅执行一次,子节点就绪后触发。在此处操作$Sprite2D是安全的。
sprite.modulate = Color.AQUA
func _process(delta: float) -> void:
# delta为距上一帧的秒数;将速率乘以delta可实现帧率无关的逻辑。
rotation_degrees += speed * delta2. Signals: declare, emit, connect (4.x Callable syntax)
2. 信号:声明、发射、连接(4.x Callable语法)
gdscript
extends Node
signal health_changed(current: int, maximum: int) # typed signal params
var health := 100
func take_damage(amount: int) -> void:
health = max(health - amount, 0)
health_changed.emit(health, 100) # 4.x: emit as a method on the signal
func _ready() -> void:
# 4.x: connect with a Callable, not a string method name.
health_changed.connect(_on_health_changed)
func _on_health_changed(current: int, maximum: int) -> void:
print("HP: %d/%d" % [current, maximum])gdscript
extends Node
signal health_changed(current: int, maximum: int) # 带类型的信号参数
var health := 100
func take_damage(amount: int) -> void:
health = max(health - amount, 0)
health_changed.emit(health, 100) # 4.x版本:通过信号对象的emit方法发射信号
func _ready() -> void:
# 4.x版本:使用Callable连接,而非字符串方法名。
health_changed.connect(_on_health_changed)
func _on_health_changed(current: int, maximum: int) -> void:
print("HP: %d/%d" % [current, maximum])3. await — pause until a timer or signal fires (replaces 3.x yield)
3. await —— 暂停直到计时器或信号触发(替代3.x版本的yield)
gdscript
func flash_then_continue() -> void:
modulate = Color.RED
await get_tree().create_timer(0.2).timeout # resume after 0.2s
modulate = Color.WHITE
# await any signal: var result = await some_node.some_signalgdscript
func flash_then_continue() -> void:
modulate = Color.RED
await get_tree().create_timer(0.2).timeout # 0.2秒后恢复执行
modulate = Color.WHITE
# 可等待任意信号:var result = await some_node.some_signal4. Lambdas, typed arrays, and safe access
4. Lambda表达式、类型化数组与安全访问
gdscript
var enemies: Array[Node] = [] # typed array
func cull_dead() -> void:
enemies = enemies.filter(func(e): return e.is_inside_tree())
func get_first_name(d: Dictionary) -> String:
return d.get("name", "unknown") # default avoids missing-key errorsgdscript
var enemies: Array[Node] = [] # 类型化数组
func cull_dead() -> void:
enemies = enemies.filter(func(e): return e.is_inside_tree())
func get_first_name(d: Dictionary) -> String:
return d.get("name", "unknown") # 使用默认值避免键缺失错误Pitfalls
常见陷阱
- 3.x → 4.x signal API changed. still works but prefer
emit_signal("x");x.emit(...)is gone — useconnect("x", self, "_on_x")with a Callable.x.connect(_on_x)is nowyield(obj, "sig").await obj.sig - is now
export var(annotation). Likewise@export var→onready,@onready→tool,@tool/remoteRPC keywords → themasterannotation.@rpc(...) - and
@onreadyin$NodePathfail — the node isn't in the tree yet. Initialize node references in_init()or with_ready().@onready - Integer division truncates. . Use
5 / 2 == 2or cast to5.0 / 2.float - vs
_process. Put_physics_processand physics inmove_and_slide(); using_physics_process(delta)makes motion frame-rate dependent._process - must be unique project-wide and is required to use the type name in other scripts or as an Inspector type.
class_name
- 3.x → 4.x版本的信号API已变更。仍可使用,但推荐使用
emit_signal("x");x.emit(...)已废弃——请使用connect("x", self, "_on_x")搭配Callable。x.connect(_on_x)现已改为yield(obj, "sig")。await obj.sig - 现已改为
export var(注解形式)。同理,@export var→onready、@onready→tool、@tool/remoteRPC关键字→master注解。@rpc(...) - 在中使用
_init()和@onready会失败——此时节点尚未加入场景树。请在$NodePath中初始化节点引用,或使用_ready()。@onready - 整数除法会截断结果。。请使用
5 / 2 == 2或转换为5.0 / 2类型。float - 与
_process的区别。将_physics_process及物理相关逻辑放在move_and_slide()中;使用_physics_process(delta)会导致运动依赖帧率。_process - 必须在项目范围内唯一,且在其他脚本中使用该类型名或作为检查器类型时是必需的。
class_name
References
参考资料
- For the full annotation list, advanced typing, and style conventions, read
.
references/annotations-and-typing.md
- 如需查看完整注解列表、高级类型用法及风格规范,请阅读。
references/annotations-and-typing.md
Related skills
相关技能
- — the scene tree, instancing, and autoloads.
godot-nodes-scenes - — event-driven architecture with signals and groups.
godot-signals-groups - — data-driven design with custom
godot-resourcestypes.Resource - — the same engine concepts using C#/.NET.
godot-csharp
- —— 场景树、实例化与自动加载。
godot-nodes-scenes - —— 基于信号与组的事件驱动架构。
godot-signals-groups - —— 使用自定义
godot-resources类型实现数据驱动设计。Resource - —— 使用C#/.NET实现相同引擎概念。
godot-csharp