Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

GDScript 风格指南

该样式指南列出了编写优雅 GDScript 的约定。目标是促进编写干净、可读的代码,促进项目、讨论和教程之间的一致性。希望这也会促进开发自动格式化工具。

由于 GDScript 与 Python 非常接近,因此本指南的灵感来自 Python 的 PEP 8 编程风格指南。

风格指南并不是硬性的规则手册。有时,您可能无法应用下面的一些规范。当这种情况发生时,请使用你最好的判断,并询问其他开发人员的见解。

一般来说,在项目和团队中保持代码的一致性比一板一眼地遵循本指南更为重要。

备注

Godot的内置脚本编辑器默认使用了很多这些约定. 让它帮助你.

下面是基于这些规范的完整的类的示例:

class_name StateMachine
extends Node
## Hierarchical State machine for the player.
##
## Initializes states and delegates engine callbacks ([method Node._physics_process],
## [method Node._unhandled_input]) to the state.


signal state_changed(previous, new)

@export var initial_state: Node
var is_active = true:
    set = set_is_active

@onready var _state = initial_state:
    get = set_state
@onready var _state_name = _state.name


func _init():
    add_to_group("state_machine")


func _enter_tree():
    print("this happens before the ready method!")


func _ready():
    state_changed.connect(_on_state_changed)
    _state.enter()


func _unhandled_input(event):
    _state.unhandled_input(event)


func _physics_process(delta):
    _state.physics_process(delta)


func transition_to(target_state_path, msg={}):
    if not has_node(target_state_path):
        return

    var target_state = get_node(target_state_path)
    assert(target_state.is_composite == false)

    _state.exit()
    self._state = target_state
    _state.enter(msg)
    Events.player_state_changed.emit(_state.name)


func set_is_active(value):
    is_active = value
    set_physics_process(value)
    set_process_unhandled_input(value)
    set_block_signals(not value)


func set_state(value):
    _state = value
    _state_name = _state.name


func _on_state_changed(previous, new):
    print("state changed")
    state_changed.emit()


class State:
    var foo = 0

    func _init():
        print("Hello!")

格式

编码和特殊字符

  • 使用换行符(LF)换行,而不是 CRLF 或 CR。(编辑器默认)

  • 在每个文件的末尾使用一个换行符。(编辑器默认)

  • 使用不带字节顺序标记UTF-8 编码。(编辑器默认)

  • 使用制表符代替空格进行缩进。(编辑器默认)

缩进

每个缩进级别必须大于包含它的代码块.

良好的 :

for i in range(10):
    print("hello")

糟糕的 :

for i in range(10):
  print("hello")

for i in range(10):
        print("hello")

使用2个缩进级别来区分续行与常规代码块.

良好的 :

effect.interpolate_property(sprite, "transform/scale",
            sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
            Tween.TRANS_QUAD, Tween.EASE_OUT)

糟糕的 :

effect.interpolate_property(sprite, "transform/scale",
    sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
    Tween.TRANS_QUAD, Tween.EASE_OUT)

此规则的例外是数组, 字典和枚举. 使用单个缩进级别来区分连续行:

良好的 :

var party = [
    "Godot",
    "Godette",
    "Steve",
]

var character_dict = {
    "Name": "Bob",
    "Age": 27,
    "Job": "Mechanic",
}

enum Tiles {
    TILE_BRICK,
    TILE_FLOOR,
    TILE_SPIKE,
    TILE_TELEPORT,
}

糟糕的 :

var party = [
        "Godot",
        "Godette",
        "Steve",
]

var character_dict = {
        "Name": "Bob",
        "Age": 27,
        "Job": "Mechanic",
}

enum Tiles {
        TILE_BRICK,
        TILE_FLOOR,
        TILE_SPIKE,
        TILE_TELEPORT,
}

行尾逗号

请在数组、字典和枚举的最后一行使用逗号。这将使版本控制中的重构更容易,Diff 也更美观,因为添加新元素时不需要修改最后一行。

良好的 :

enum Tiles {
    TILE_BRICK,
    TILE_FLOOR,
    TILE_SPIKE,
    TILE_TELEPORT,
}

糟糕的 :

enum Tiles {
    TILE_BRICK,
    TILE_FLOOR,
    TILE_SPIKE,
    TILE_TELEPORT
}

单行列表中不需要行尾逗号,因此在这种情况下不要添加它们。

良好的 :

enum Tiles {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}

糟糕的 :

enum Tiles {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT,}

空白行

用两个空行包围函数和类定义:

func heal(amount):
    health += amount
    health = min(health, max_health)
    health_changed.emit(health)


func take_damage(amount, effect=null):
    health -= amount
    health = max(0, health)
    health_changed.emit(health)

函数内部使用一个空行来分隔逻辑部分.

备注

在类参考和本文档的短代码片段中,我们会在类和函数定义之间使用单个空行。

行的长度

把每行代码控制在100个字符以内.

如果可以的话, 尽量把行控制在80个字符以下. 这有助于在小屏幕上阅读代码, 并在外部文本编辑器中并排打开两个脚本. 例如, 在查看差异修订时.

一条语句一行

不要在一行上合并多个语句. 不要像C语言那样, 不能使用单行条件语句(三元运算符除外).

良好的 :

if position.x > width:
    position.x = 0

if flag:
    print("flagged")

糟糕的 :

if position.x > width: position.x = 0

if flag: print("flagged")

该规则的唯一例外是三元运算符:

next_state = "idle" if is_on_floor() else "fall"

为可读性格式化多行语句

如果你的 if 语句特别长,或者是嵌套的三元表达式时,把它们拆分成多行可以提高可读性。因为这些连续的行仍然属于同一个表达式,应该缩进两级而不是一级。

GDScript 允许使用括号或反斜杠将语句拆成多行。本风格指南倾向于使用括号,因为重构起来更简单。使用反斜杠的话,你必须保证最后一行的末尾没有反斜杠。而如果是括号,你就不必担心最后一行的反斜杠问题。

把条件表达式拆分成多行时,andor 关键字应当放在下一行的开头,而不是上一行的结尾。

良好的 :

var angle_degrees = 135
var quadrant = (
        "northeast" if angle_degrees <= 90
        else "southeast" if angle_degrees <= 180
        else "southwest" if angle_degrees <= 270
        else "northwest"
)

var position = Vector2(250, 350)
if (
        position.x > 200 and position.x < 400
        and position.y > 300 and position.y < 400
):
    pass

糟糕的 :

var angle_degrees = 135
var quadrant = "northeast" if angle_degrees <= 90 else "southeast" if angle_degrees <= 180 else "southwest" if angle_degrees <= 270 else "northwest"

var position = Vector2(250, 350)
if position.x > 200 and position.x < 400 and position.y > 300 and position.y < 400:
    pass

避免不必要的圆括号

避免表达式和条件语句中的括号。除非需要修改操作顺序或者是在拆分多行,否则它们只会降低可读性。

良好的 :

if is_colliding():
    queue_free()

糟糕的 :

if (is_colliding()):
    queue_free()

布尔运算

首选布尔运算符的英文版本,因为它们是最易懂的:

  • 使用 and 代替 &&

  • 使用 or 代替 ||

  • Use not instead of !.

也可以在布尔运算符周围使用括号来清除任何歧义。这可以使长表达式更容易阅读。

良好的 :

if (foo and bar) or not baz:
    print("condition is true")

糟糕的 :

if foo && bar || !baz:
    print("condition is true")

注释间距

普通注释开头应该留一个空格,但如果是为了停用代码而将其注释掉则不需要留。这样可以用来区分文本注释和停用的代码。

良好的 :

# This is a comment.
#print("This is disabled code")

糟糕的 :

#This is a comment.
# print("This is disabled code")

备注

在脚本编辑器中,要切换已注释的选定代码,请按 Ctrl + K。此功能在选定行的开头添加一个 # 注释符号。

空格

请始终在运算符前后和逗号后使用一个空格。同时,请避免在字典引用和函数调用中使用多余的空格。

良好的 :

position.x = 5
position.y = target_position.y + 10
dict["key"] = 5
my_array = [4, 5, 6]
print("foo")

糟糕的 :

position.x=5
position.y = mpos.y+10
dict ["key"] = 5
myarray = [4,5,6]
print ("foo")

不要使用空格来垂直对齐表达式:

x        = 100
y        = 100
velocity = 500

引号

尽量使用双引号,除非单引号可以让字符串中需要转义的字符变少。见如下示例:

# Normal string.
print("hello world")

# Use double quotes as usual to avoid escapes.
print("hello 'world'")

# Use single quotes as an exception to the rule to avoid escapes.
print('hello "world"')

# Both quote styles would require 2 escapes; prefer double quotes if it's a tie.
print("'hello' \"world\"")

数字

不要忽略浮点数中的前导或后缀零。否则,这会使它们的可读性降低,很难一眼与整数区分开。

良好的 :

var float_number = 0.234
var other_float_number = 13.0

糟糕的 :

var float_number = .234
var other_float_number = 13.

对于十六进制数字,请使用小写字母,因为它们较矮,使数字更易于阅读。

良好的 :

var hex_number = 0xfb8c0b

糟糕的 :

var hex_number = 0xFB8C0B

利用 GDScript 的文字下划线,使大数字更易读。

良好的 :

var large_number = 1_234_567_890
var large_hex_number = 0xffff_f8f8_0000
var large_bin_number = 0b1101_0010_1010
# Numbers lower than 1000000 generally don't need separators.
var small_number = 12345

糟糕的 :

var large_number = 1234567890
var large_hex_number = 0xfffff8f80000
var large_bin_number = 0b110100101010
# Numbers lower than 1000000 generally don't need separators.
var small_number = 12_345

命名约定

这些命名约定遵循 Godot 引擎风格. 打破这些都会使你的代码与内置的命名约定冲突, 导致风格不一致的代码.

文件命名

文件名用 snake_case 命名法,对于有名字的类,将其名字从 PascalCase 命名转化为 snake_case:

# This file should be saved as `weapon.gd`.
class_name Weapon
extends Node
# This file should be saved as `yaml_parser.gd`.
class_name YAMLParser
extends Object

这种命名于 Godot 源码中的 C++ 文件命名保持了一致. 这也防止了由 Windows 导出到其他大小写敏感平台时发生的问题.

类与节点

对类和节点名称使用帕斯卡命名法(PascalCase):

extends CharacterBody3D

将类加载到常量或变量时同样适用:

const Weapon = preload("res://weapon.gd")

函数与变量

函数与变量使用 snake_case 命名:

var particle_effect
func load_level():

在用户必须覆盖的虚方法、私有函数、私有变量前加一个下划线(_):

var _counter = 0
func _recalculate_path():

信号

用过去时态来命名信号:

signal door_opened
signal score_changed

常数和枚举

使用 CONSTANT_CASE, 全部大写, 用下划线(_)分隔单词 :

const MAX_SPEED = 200

对枚举的名称使用 PascalCase,对其成员使用 CONSTANT_CASE, 因为它们是常量:

enum Element {
    EARTH,
    WATER,
    AIR,
    FIRE,
}

代码顺序

第一节主要讨论代码顺序. 有关格式, 请参见 格式. 有关命名约定, 请参见 命名约定.

我们建议按以下方式组织GDScript代码:

01. @tool
02. class_name
03. extends
04. # docstring

05. signals
06. enums
07. constants
08. @export variables
09. public variables
10. private variables
11. @onready variables

12. optional built-in virtual _init method
13. optional built-in virtual _enter_tree() method
14. built-in virtual _ready method
15. remaining built-in virtual methods
16. public methods
17. private methods
18. subclasses

我们优化了顺序, 使从上到下阅读代码变得容易, 帮助第一次阅读代码的开发人员了解代码的工作原理, 并避免与变量声明顺序相关的错误.

此代码顺序遵循四个经验法则:

  1. 首先是属性和信号, 然后是方法.

  2. 公共变量优先于私有变量.

  3. 虚回调出现在类的接口之前.

  4. 对象的构造和初始化函数 _init_ready 在修改对象的函数之前运行.

类声明

If the code is meant to run in the editor, place the @tool annotation on the first line of the script.

Follow with the class_name if necessary. You can turn a GDScript file into a global type in your project using this feature. For more information, see GDScript reference.

Then, add the extends keyword if the class extends a built-in type.

Following that, you should have the class's optional documentation comments. You can use that to explain the role of your class to your teammates, how it works, and how other developers should use it, for example.

class_name MyNode
extends Node
## A brief description of the class's role and functionality.
##
## The description of the script, what it can do,
## and any further detail.

信号和属性

先声明信号, 后跟属性(即成员变量), 它们都在文档注释(docstring)之后.

枚举应该在信号之后, 因为您可以将它们用作其他属性的导出提示.

然后, 按该顺序写入常量, 导出变量, 公共变量, 私有变量和 onready 变量.

signal player_spawned(position)

enum Jobs {KNIGHT, WIZARD, ROGUE, HEALER, SHAMAN}

const MAX_LIVES = 3

@export var job: Jobs = Jobs.KNIGHT
@export var max_health = 50
@export var attack = 5

var health = max_health:
    set(new_health):
        health = new_health

var _speed = 300.0

@onready var sword = get_node("Sword")
@onready var gun = get_node("Gun")

备注

GDScript编译器在 _ready 函数回调之前计算onready变量. 您可以使用它来缓存节点依赖项, 也就是说, 在您的类所依赖的场景中获取子节点. 这就是上面的例子所展示的.

成员变量

如果变量只在方法中使用, 勿声明其为成员变量, 因为我们难以定位在何处使用了该变量. 相反, 你应该将它们在方法内部定义为局部变量.

局部变量

声明局部变量的位置离首次使用它的位置越近越好. 这让人更容易跟上代码的思路, 而不需要上下翻找该变量的声明位置.

方法和静态函数

在类的属性之后是方法.

_init() 回调方法开始, 引擎将在创建内存对象时调用该方法. 接下来是 _ready() 回调, 当Godot向场景树添加一个节点时调用它.

这些函数应该声明在脚本最前面, 因为它们显示了对象是如何初始化的.

_unhandling_input()_physics_process 等其他内置的虚回调应该放在后面。它们控制对象的主循环和与游戏引擎的交互。

类的其余接口, 公共和私有方法, 都是按照这个顺序出现的.

func _init():
    add_to_group("state_machine")


func _ready():
    state_changed.connect(_on_state_changed)
    _state.enter()


func _unhandled_input(event):
    _state.unhandled_input(event)


func transition_to(target_state_path, msg={}):
    if not has_node(target_state_path):
        return

    var target_state = get_node(target_state_path)
    assert(target_state.is_composite == false)

    _state.exit()
    self._state = target_state
    _state.enter(msg)
    Events.player_state_changed.emit(_state.name)


func _on_state_changed(previous, new):
    print("state changed")
    state_changed.emit()

静态类型

从Godot 3.1开始,GDScript支持 可选的静态类型.

声明类型

要声明变量的类型, 使用 <variable>: <type>:

var health: int = 0

要声明函数的返回类型, 使用``-> <type>``:

func heal(amount: int) -> void:

推断类型

In most cases you can let the compiler infer the type, using :=. Prefer := when the type is written on the same line as the assignment, otherwise prefer writing the type explicitly.

良好的 :

var health: int = 0 # The type can be int or float, and thus should be stated explicitly.
var direction := Vector3(1, 2, 3) # The type is clearly inferred as Vector3.

Include the type hint when the type is ambiguous, and omit the type hint when it's redundant.

糟糕的 :

var health := 0 # Typed as int, but it could be that float was intended.
var direction: Vector3 = Vector3(1, 2, 3) # The type hint has redundant information.

# What type is this? It's not immediately clear to the reader, so it's bad.
var value := complex_function()

In some cases, the type must be stated explicitly, otherwise the behavior will not be as expected because the compiler will only be able to use the function's return type. For example, get_node() cannot infer a type unless the scene or file of the node is loaded in memory. In this case, you should set the type explicitly.

良好的 :

@onready var health_bar: ProgressBar = get_node("UI/LifeBar")

或者,你也可以使用 as 关键字来转换返回类型,这个类型会被用于推导变量的类型。

@onready var health_bar := get_node("UI/LifeBar") as ProgressBar
# health_bar will be typed as ProgressBar

这种做法也比第一种更类型安全

糟糕的 :

# The compiler can't infer the exact type and will use Node
# instead of ProgressBar.
@onready var health_bar := get_node("UI/LifeBar")