gdscript样式指南¶
描述¶
这个样式指南列出了编写优雅gdscript的惯例。目标是鼓励编写干净、可读的代码,并促进项目、讨论和教程之间的一致性。希望这也能鼓励开发自动格式化工具。
由于gdscript接近于python,因此本指南的灵感来自于python的 PEP 8 编程样式指南。
注解
默认情况下,Godot的内置脚本编辑器使用了很多这样的约定。让它帮助你。
代码结构¶
缩进¶
缩进类型:制表符 (编辑器默认值)
缩进大小:4 (编辑器默认值)
每个缩进级别应该比包含它的块大一个。
Good :
for i in range(10):
print("hello")
Bad :
for i in range(10):
print("hello")
for i in range(10):
print("hello")
使用两个缩进级别来区分连续行和常规代码块。
Good :
effect.interpolate_property(sprite, 'transform/scale',
sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
Tween.TRANS_QUAD, Tween.EASE_OUT)
Bad :
effect.interpolate_property(sprite, 'transform/scale',
sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
Tween.TRANS_QUAD, Tween.EASE_OUT)
空白行¶
用两条空行环绕函数和类定义:
func heal(amount):
health += amount
health = min(health, max_health)
emit_signal("health_changed", health)
func take_damage(amount, effect=null):
health -= amount
health = max(0, health)
emit_signal("health_changed", health)
在函数内部使用一个空行来分隔逻辑部分。
每行一个语句¶
不要在一行中组合多个语句。不,C程序员,不使用单行条件语句(三元运算符除外)!
Good :
if position.x > width:
position.x = 0
if flag:
print("flagged")
Bad :
if position.x > width: position.x = 0
if flag: print("flagged")
避免不必要的括号¶
避免在表达式和条件语句中使用括号。除非操作顺序需要,否则它们只会降低可读性。
Good :
if is_colliding():
queue_free()
Bad :
if (is_colliding()):
queue_free()
空白¶
始终在运算符周围和逗号后使用一个空格。在字典引用和函数调用中避免额外的空格,或者创建“列”。
Good :
position.x = 5
position.y = mpos.y + 10
dict['key'] = 5
myarray = [4, 5, 6]
print('foo')
Bad :
position.x=5
position.y = mpos.y+10
dict ['key'] = 5
myarray = [4,5,6]
print ('foo')
NEVER :
x = 100
y = 100
velocity = 500
命名约定¶
这些命名约定遵循godot引擎样式。打破这些将使您的代码与内置的命名约定冲突,这是丑陋的。
类和节点¶
使用Pascalcase: extends KinematicBody
同样,当将类加载到常量或变量中时:
const MyCoolNode = preload('res://my_cool_node.gd')
常量¶
使用常量大小写,全部大写,带下划线 (_) 分词: const MAX_SPEED = 200
静态类型¶
由于godot 3.1,gdscript支持 optional static typing .
类型提示¶
将冒号放在变量名后面,不带空格,并让gdscript编译器尽可能推断变量的类型。
Good :
onready var health_bar: ProgressBar = get_node("UI/LifeBar")
var health := 0 # The compiler will use the int type
Bad :
# The compiler can't infer the exact type and will use Node
# instead of ProgressBar
onready var health_bar := get_node("UI/LifeBar")
当让编译器推断类型提示时,将冒号和等号写在一起: :=
.
var health := 0 # The compiler will use the int type
定义函数时,在返回类型箭头的两侧添加一个空格。
func heal(amount: int) -> void: