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 reference

GDScript is a high-level, object-oriented, imperative, and gradually typed programming language built for Godot. It uses an indentation-based syntax similar to languages like Python. Its goal is to be optimized for and tightly integrated with Godot Engine, allowing great flexibility for content creation and integration.

GDScript is entirely independent from Python and is not based on it.

历史

备注

关于GDScript历史的文档已被移至 常见问题 中.

GDScript的示例

Some people can learn better by taking a look at the syntax, so here's an example of how GDScript looks.

# Everything after "#" is a comment.
# A file is a class!

# (optional) icon to show in the editor dialogs:
@icon("res://path/to/optional/icon.svg")

# (optional) class definition:
class_name MyClass

# Inheritance:
extends BaseClass


# Member variables.
var a = 5
var s = "Hello"
var arr = [1, 2, 3]
var dict = {"key": "value", 2: 3}
var other_dict = {key = "value", other_key = 2}
var typed_var: int
var inferred_type := "String"

# Constants.
const ANSWER = 42
const THE_NAME = "Charly"

# Enums.
enum {UNIT_NEUTRAL, UNIT_ENEMY, UNIT_ALLY}
enum Named {THING_1, THING_2, ANOTHER_THING = -1}

# Built-in vector types.
var v2 = Vector2(1, 2)
var v3 = Vector3(1, 2, 3)


# Functions.
func some_function(param1, param2, param3):
    const local_const = 5

    if param1 < local_const:
        print(param1)
    elif param2 > 5:
        print(param2)
    else:
        print("Fail!")

    for i in range(20):
        print(i)

    while param2 != 0:
        param2 -= 1

    match param3:
        3:
            print("param3 is 3!")
        _:
            print("param3 is not 3!")

    var local_var = param1 + 3
    return local_var


# Functions override functions with the same name on the base/super class.
# If you still want to call them, use "super":
func something(p1, p2):
    super(p1, p2)


# It's also possible to call another function in the super class:
func other_something(p1, p2):
    super.something(p1, p2)


# Inner class
class Something:
    var a = 10


# Constructor
func _init():
    print("Constructed!")
    var lv = Something.new()
    print(lv.a)

如果你以前有使用C, C++或C#之类的静态类型语言的经验, 但以前从未使用过动态类型的语言, 建议你阅读此教程: GDScript:动态语言简介.

语言

在下面, 概述了GDScript. 详细信息, 例如哪些方法可用于数组或其他对象, 可以在链接的类描述中查找到这些方法.

标识符

任何仅限于字母字符( azAZ ), 数字( 09 )和 _ 的字符串都可以作为标识符. 此外, 标识符不能以数字开头. 标识符区分大小写( fooFOO 是不同的).

Identifiers may also contain most Unicode characters part of UAX#31. This allows you to use identifier names written in languages other than English. Unicode characters that are considered "confusable" for ASCII characters and emoji are not allowed in identifiers.

关键字

以下是该语言支持的关键字列表。由于关键字是保留字(记号),它们不能用作标识符。操作符(如 innotandor)以及下面列出的内置类型的名称也是保留的。

如果你想深入了解关键字,它们的定义在 GDScript 词法分析器中。

关键字

描述

if

if/else/elif.

elif

if/else/elif.

else

if/else/elif.

for

for.

while

while.

match

match.

break

退出当前 forwhile 循环的执行.

continue

立即跳到 forwhile 循环的下一个迭代.

pass

在语法上要求语句但不希望执行代码的地方使用, 例如在空函数中.

return

从函数返回一个值.

class

Defines a class.

class_name

Defines the script as a globally accessible class with the specified name.

extends

定义用当前类扩展什么类.

is

测试变量是否扩展给定的类, 或者是否是给定的内置类型.

in

Tests whether a value is within a string, list, range, dictionary, or node. When used with for, it iterates through them instead of testing.

as

如果可能, 将值转换为给定类型.

self

引用当前类实例.

signal

定义信号。

func

定义函数。

static

Defines a static function or a static member variable.

const

定义常量。

enum

定义枚举。

var

定义变量。

breakpoint

Editor helper for debugger breakpoints. Unlike breakpoints created by clicking in the gutter, breakpoint is stored in the script itself. This makes it persistent across different machines when using version control.

preload

预加载一个类或变量. 请参见 类作为资源.

await

Waits for a signal or a coroutine to finish. See Awaiting for signals or coroutines.

yield

Previously used for coroutines. Kept as keyword for transition.

assert

断言条件,如果失败则记录错误。在非调试版本中被忽略。参见 Assert 关键字

void

Used to represent that a function does not return any value.

PI

圆周率常量.

TAU

TAU 常量.

INF

Infinity constant. Used for comparisons and as result of calculations.

NAN

NAN (not a number) constant. Used as impossible result from calculations.

运算符

下面是支持的运算符列表及其优先级(越上面越高).

运算符

描述

( )

Grouping (highest priority)

Parentheses are not really an operator, but allow you to explicitly specify the precedence of an operation.

x[index]

Subscription

x.attribute

属性引用

foo()

函数调用

await x

Awaiting for signals or coroutines

x is Node

Type checking

See also is_instance_of() function.

x ** y

Power

Multiplies x by itself y times, similar to calling pow() function.

Note: In GDScript, the ** operator is left-associative. See a detailed note after the table.

~x

按位取反

+x
-x

Identity / Negation

x * y
x / y
x % y

乘法/除法/余数

The % operator is additionally used for format strings.

Note: These operators have the same behavior as C++, which may be unexpected for users coming from Python, JavaScript, etc. See a detailed note after the table.

x + y
x - y

Addition (or Concatenation) / Subtraction

x << y
x >> y

位移位

x & y

按位与

x ^ y

按位异或

x | y

按位或

x == y
x != y
x < y
x > y
x <= y
x >= y

Comparison

See a detailed note after the table.

x in y
x not in y

Inclusion checking

in is also used with the for keyword as part of the syntax.

not x
!x

Boolean NOT and its unrecommended alias

x and y
x && y

Boolean AND and its unrecommended alias

x or y
x || y

Boolean OR and its unrecommended alias

true_expr if cond else false_expr

三元 if/else

x as Node

Type casting

x = y
x += y
x -= y
x *= y
x /= y
x **= y
x %= y
x &= y
x |= y
x ^= y
x <<= y
x >>= y

赋值(最低优先级)

You cannot use an assignment operator inside an expression.

备注

The behavior of some operators may differ from what you expect:

  1. If both operands of the / operator are int, then integer division is performed instead of fractional. For example 5 / 2 == 2, not 2.5. If this is not desired, use at least one float literal (x / 2.0), cast (float(x) / y), or multiply by 1.0 (x * 1.0 / y).

  2. The % operator is only available for ints, for floats use the fmod() function.

  3. For negative values, the % operator and fmod() use truncation instead of rounding towards negative infinity. This means that the remainder has a sign. If you need the remainder in a mathematical sense, use the posmod() and fposmod() functions instead.

  4. The ** operator is left-associative. This means that 2 ** 2 ** 3 is equal to (2 ** 2) ** 3. Use parentheses to explicitly specify precedence you need, for example 2 ** (2 ** 3).

  5. The == and != operators sometimes allow you to compare values of different types (for example, 1 == 1.0 is true), but in other cases it can cause a runtime error. If you're not sure about the types of the operands, you can safely use the is_same() function (but note that it is more strict about types and references). To compare floats, use the is_equal_approx() and is_zero_approx() functions instead.

字面量

字面量

类型

45

基数为 10 的整数

0x8f51

基数为 16 的(十六进制)整数

0b101010

基数为 2 的(二进制)整数

3.14, 58.1e-10

浮点数(实数)

"Hello", 'Hi'

字符串

"""Hello"""

多行字符串

&"name"

StringName

^"Node/Label"

NodePath

$NodePath

get_node("NodePath") 的简写

%UniqueNode

Shorthand for get_node("%UniqueNode")

整数和浮点数可以用 _ 来分隔,使其更易读。以下表示数字的方式都是有效的:

12_345_678  # Equal to 12345678.
3.141_592_7  # Equal to 3.1415927.
0x8080_0000_ffff  # Equal to 0x80800000ffff.
0b11_00_11_00  # Equal to 0b11001100.

Annotations

There are some special tokens in GDScript that act like keywords but are not, they are annotations instead. Every annotation start with the @ character and is specified by a name. A detailed description and example for each annotation can be found inside the GDScript class reference.

Annotations affect how the script is treated by external tools and usually don't change the behavior.

For instance, you can use it to export a value to the editor:

@export_range(1, 100, 1, "or_greater")
var ranged_var: int = 50

For more information about exporting properties, read the GDScript exports article.

Any constant expression compatible with the required argument type can be passed as an annotation argument value:

const MAX_SPEED = 120.0

@export_range(0.0, 0.5 * MAX_SPEED)
var initial_speed: float = 0.25 * MAX_SPEED

Annotations can be specified one per line or all in the same line. They affect the next statement that isn't an annotation. Annotations can have arguments sent between parentheses and separated by commas.

Both of these are the same:

@annotation_a
@annotation_b
var variable

@annotation_a @annotation_b var variable

@onready annotation

使用节点时, 通常希望将对场景部分的引用保留在变量中. 由于仅在进入活动场景树时才保证要配置场景, 因此只有在调用 Node._ready() 时才能获得子节点.

var my_label


func _ready():
    my_label = get_node("MyLabel")

This can get a little cumbersome, especially when nodes and external references pile up. For this, GDScript has the @onready annotation, that defers initialization of a member variable until _ready() is called. It can replace the above code with a single line:

@onready var my_label = get_node("MyLabel")

警告

Applying @onready and any @export annotation to the same variable doesn't work as you might expect. The @onready annotation will cause the default value to be set after the @export takes effect and will override it:

@export var a = "init_value_a"
@onready @export var b = "init_value_b"

func _init():
    prints(a, b) # init_value_a <null>

func _notification(what):
    if what == NOTIFICATION_SCENE_INSTANTIATED:
        prints(a, b) # exported_value_a exported_value_b

func _ready():
    prints(a, b) # exported_value_a init_value_b

Therefore, the ONREADY_WITH_EXPORT warning is generated, which is treated as an error by default. We do not recommend disabling or ignoring it.

注释

任何从 # 开始到行尾的内容都会被忽略, 并被视为注释.

# This is a comment.

Line continuation

A line of code in GDScript can be continued on the next line by using a backslash (\). Add one at the end of a line and the code on the next line will act like it's where the backslash is. Here is an example:

var a = 1 + \
2

A line can be continued multiple times like this:

var a = 1 + \
4 + \
10 + \
4

内置类型

Built-in types are stack-allocated. They are passed as values. This means a copy is created on each assignment or when passing them as arguments to functions. The exceptions are Object, Array, Dictionary, and packed arrays (such as PackedByteArray), which are passed by reference so they are shared. All arrays, Dictionary, and some objects (Node, Resource) have a duplicate() method that allows you to make a copy.

基本内置类型

GDScript 中的变量可以赋值为不同的内置类型。

null

null 是一个空数据类型,不包含任何信息,不能赋值为任何其他值。

bool

“boolean”(布尔)的缩写,只能包含 truefalse

int

Short for "integer", it stores whole numbers (positive and negative). It is stored as a 64-bit value, equivalent to int64_t in C++.

float

Stores real numbers, including decimals, using floating-point values. It is stored as a 64-bit value, equivalent to double in C++. Note: Currently, data structures such as Vector2, Vector3, and PackedFloat32Array store 32-bit single-precision float values.

String

A sequence of characters in Unicode format. String literals can contain the following escape sequences:

转义序列

转义为

\n

换行(line feed,LF)

\t

水平制表符(tab)

\r

回车(carriage return,CR)

\a

警报(蜂鸣/响铃)

\b

退格键(Backspace)

\f

换页符(form feed,FF)

\v

垂直制表符(tab)

\"

双引号

\'

单引号

\\

反斜杠

\uXXXX

UTF-16 Unicode codepoint XXXX (hexadecimal, case-insensitive)

\UXXXXXX

UTF-32 Unicode codepoint XXXXXX (hexadecimal, case-insensitive)

There are two ways to represent an escaped Unicode character above 0xFFFF:

Also, using \ followed by a newline inside a string will allow you to continue it in the next line, without inserting a newline character in the string itself.

GDScript also supports format strings.

StringName

An immutable string that allows only one instance of each name. They are slower to create and may result in waiting for locks when multithreading. In exchange, they're very fast to compare, which makes them good candidates for dictionary keys.

NodePath

A pre-parsed path to a node or a node property. It can be easily assigned to, and from, a String. They are useful to interact with the tree to get a node, or affecting properties like with Tweens.

内置向量类型

Vector2

2D 向量类型,包含 xy 字段,也可以像数组一样访问。

Vector2i

Same as a Vector2 but the components are integers. Useful for representing items in a 2D grid.

Rect2

2D 矩形类型,包含两个向量字段: positionsize。还包含一个 end 字段,即 position + size

Vector3

3D 向量类型,包含 xyz 字段,也可以像数组一样访问。

Vector3i

Same as Vector3 but the components are integers. Can be use for indexing items in a 3D grid.

Transform2D

用于2D变换的3x2矩阵.

Plane

3D平面类型的标准形式包含一个 normal 向量字段以及一个 d 标量距离.

Quaternion

四元数是一种用于表示3D旋转的数据类型. 它对于内插旋转很有用.

AABB

轴对齐边界框(或3D框)包含两个向量字段: positionsize. 还包含一个 end 字段, 即 position + size.

Basis

3×3矩阵被用于3D旋转与缩放. 其包含3个向量字段(x, yz) 并且可以像3D向量数组那样访问.

Transform3D

3D 变换包含一个 Basis(基)字段 basis 和一个 Vector3 字段 origin

引擎内置类型

Color

颜色数据类型包含 r, g, b, 和 a 字段. 它也可以作为 h, s, 和 v 来访问色相/饱和度/值.

RID

资源ID(RID). 服务使用通用的RID来引用不透明数据.

Object

任何非内置类型的基类.

容器内置类型

Array

任意对象类型的泛型序列,包括其他数组或字典(见下文)。数组可以动态调整大小。数组索引从 0 开始。负索引表示从尾部开始计数.

var arr = []
arr = [1, 2, 3]
var b = arr[1] # This is 2.
var c = arr[arr.size() - 1] # This is 3.
var d = arr[-1] # Same as the previous line, but shorter.
arr[0] = "Hi!" # Replacing value 1 with "Hi!".
arr.append(4) # Array is now ["Hi!", 2, 3, 4].

Typed arrays

Godot 4.0 added support for typed arrays. On write operations, Godot checks that element values match the specified type, so the array cannot contain invalid values. The GDScript static analyzer takes typed arrays into account, however array methods like front() and back() still have the Variant return type.

Typed arrays have the syntax Array[Type], where Type can be any Variant type, native or user class, or enum. Nested array types (like Array[Array[int]]) are not supported.

var a: Array[int]
var b: Array[Node]
var c: Array[MyClass]
var d: Array[MyEnum]
var e: Array[Variant]

Array and Array[Variant] are the same thing.

备注

Arrays are passed by reference, so the array element type is also an attribute of the in-memory structure referenced by a variable in runtime. The static type of a variable restricts the structures that it can reference to. Therefore, you cannot assign an array with a different element type, even if the type is a subtype of the required type.

If you want to convert a typed array, you can create a new array and use the Array.assign() method:

var a: Array[Node2D] = [Node2D.new()]

# (OK) You can add the value to the array because `Node2D` extends `Node`.
var b: Array[Node] = [a[0]]

# (Error) You cannot assign an `Array[Node2D]` to an `Array[Node]` variable.
b = a

# (OK) But you can use the `assign()` method instead. Unlike the `=` operator,
# the `assign()` method copies the contents of the array, not the reference.
b.assign(a)

The only exception was made for the Array (Array[Variant]) type, for user convenience and compatibility with old code. However, operations on untyped arrays are considered unsafe.

Packed arrays

GDScript 数组在内存中线性分配以提高速度。但是,大型数组(包含数万个元素)可能会导致内存碎片。如果在意这个问题,可以使用特定类型的数组。它们只接受单个数据类型。它们避免了内存碎片并使用更少的内存,但是它们是原子的,运行起来容易比通用数组要慢。因此,建议仅将它们用于大型数据集:

Dictionary

关联容器,包含的值通过唯一的键进行引用。

var d = {4: 5, "A key": "A value", 28: [1, 2, 3]}
d["Hi!"] = 0
d = {
    22: "value",
    "some_key": 2,
    "other_key": [2, 3, 4],
    "more_key": "Hello"
}

还支持 Lua 风格的 table 语法。Lua 风格使用 = 而不是 :,并且不使用引号来标记字符串键(这样要写的东西会稍微少一些)。但是请注意,与任何 GDScript 标识符一样,以这种形式编写的键不能以数字开头。

var d = {
    test22 = "value",
    some_key = 2,
    other_key = [2, 3, 4],
    more_key = "Hello"
}

若要向现有字典添加键,请像访问现有键一样访问它,并给它赋值:

var d = {} # Create an empty Dictionary.
d.waiting = 14 # Add String "waiting" as a key and assign the value 14 to it.
d[4] = "hello" # Add integer 4 as a key and assign the String "hello" as its value.
d["Godot"] = 3.01 # Add String "Godot" as a key and assign the value 3.01 to it.

var test = 4
# Prints "hello" by indexing the dictionary with a dynamic key.
# This is not the same as `d.test`. The bracket syntax equivalent to
# `d.test` is `d["test"]`.
print(d[test])

备注

方括号语法不仅可以用在 Dictionary 上,而且还可以用来存取任何 Object 的属性。请记住,尝试读取不存在的属性会引发脚本错误。要避免这一点,可以换用 Object.get()Object.set() 方法。

Signal

A signal is a message that can be emitted by an object to those who want to listen to it. The Signal type can be used for passing the emitter around.

Signals are better used by getting them from actual objects, e.g. $Button.button_up.

Callable

Contains an object and a function, which is useful for passing functions as values (e.g. when connecting to signals).

Getting a method as a member returns a callable. var x = $Sprite2D.rotate will set the value of x to a callable with $Sprite2D as the object and rotate as the method.

You can call it using the call method: x.call(PI).

数据

变量

变量可以作为类成员存在,也可以作为函数的局部变量存在。它们是用 var 关键字创建的,并且可以在初始化时指定一个值。

var a # Data type is 'null' by default.
var b = 5
var c = 3.8
var d = b + c # Variables are always initialized in order.

变量可以选择具有类型声明. 指定类型时, 变量将强制始终具有相同的类型, 并且试图分配不兼容的值将引发错误.

类型在变量声明中使用 :(冒号)符号在变量名后面指定,后面是类型。

var my_vector2: Vector2
var my_node: Node = Sprite2D.new()

如果在声明中初始化变量,则可以推断类型,因此可以省略类型名称:

var my_vector2 := Vector2() # 'my_vector2' is of type 'Vector2'.
var my_node := Sprite2D.new() # 'my_node' is of type 'Sprite2D'.

类型推断只有在指定的值具有定义的类型时才可能, 否则将引发错误.

有效的类型有:

  • 内置类型(Array, Vector2, int, String, 等).

  • 引擎类(Node, Resource, Reference, 等).

  • 常量名, 如果它们包含脚本资源(MyScript 如果声明 const MyScript = preload("res://my_script.gd")).

  • 在同一个脚本中的其他类, 遵循作用域(如果在相同作用域内, 在 class InnerClass 中声明 class NestedClass 得到 InnerClass.NestedClass ).

  • 脚本类使用 class_name 关键字声明.

  • Autoloads registered as singletons.

备注

While Variant is a valid type specification, it's not an actual type. It only means there's no set type and is equivalent to not having a static type at all. Therefore, inference is not allowed by default for Variant, since it's likely a mistake.

You can turn off this check, or make it only a warning, by changing it in the project settings. See GDScript 警告系统 for details.

Static variables

A class member variable can be declared static:

static var a

Static variables belong to the class, not instances. This means that static variables share values between multiple instances, unlike regular member variables.

From inside a class, you can access static variables from any function, both static and non-static. From outside the class, you can access static variables using the class or an instance (the second is not recommended as it is less readable).

备注

The @export and @onready annotations cannot be applied to a static variable. Local variables cannot be static.

The following example defines a Person class with a static variable named max_id. We increment the max_id in the _init() function. This makes it easy to keep track of the number of Person instances in our game.

# person.gd
class_name Person

static var max_id = 0

var id
var name

func _init(p_name):
    max_id += 1
    id = max_id
    name = p_name

In this code, we create two instances of our Person class and check that the class and every instance have the same max_id value, because the variable is static and accessible to every instance.

# test.gd
extends Node

func _ready():
    var person1 = Person.new("John Doe")
    var person2 = Person.new("Jane Doe")

    print(person1.id) # 1
    print(person2.id) # 2

    print(Person.max_id)  # 2
    print(person1.max_id) # 2
    print(person2.max_id) # 2

Static variables can have type hints, setters and getters:

static var balance: int = 0

static var debt: int:
    get:
        return -balance
    set(value):
        balance = -value

A base class static variable can also be accessed via a child class:

class A:
    static var x = 1

class B extends A:
    pass

func _ready():
    prints(A.x, B.x) # 1 1
    A.x = 2
    prints(A.x, B.x) # 2 2
    B.x = 3
    prints(A.x, B.x) # 3 3

@static_unload annotation

Since GDScript classes are resources, having static variables in a script prevents it from being unloaded even if there are no more instances of that class and no other references left. This can be important if static variables store large amounts of data or hold references to other project resources, such as scenes. You should clean up this data manually, or use the @static_unload annotation if static variables don't store important data and can be reset.

警告

Currently, due to a bug, scripts are never freed, even if @static_unload annotation is used.

Note that @static_unload applies to the entire script (including inner classes) and must be placed at the top of the script, before class_name and extends:

@static_unload
class_name MyNode
extends Node

See also Static functions and Static constructor.

转换

分配给类型变量的值必须具有兼容的类型. 如果需要将值强制转换为特定类型, 特别是对于对象类型, 则可以使用强制转换运算符 as.

如果值是相同类型或转换类型的子类型, 则在对象类型之间进行转换会导致相同的对象.

var my_node2D: Node2D
my_node2D = $Sprite2D as Node2D # Works since Sprite2D is a subtype of Node2D.

如果该值不是子类型, 则强制转换操作将产生 null 值.

var my_node2D: Node2D
my_node2D = $Button as Node2D # Results in 'null' since a Button is not a subtype of Node2D.

对于内置类型, 如果可能, 将对其进行强制转换, 否则引擎将引发错误.

var my_int: int
my_int = "123" as int # The string can be converted to int.
my_int = Vector2() as int # A Vector2 can't be converted to int, this will cause an error.

与场景树进行交互时,强制转换对于获得更好的类型安全变量也很有用:

# Will infer the variable to be of type Sprite2D.
var my_sprite := $Character as Sprite2D

# Will fail if $AnimPlayer is not an AnimationPlayer, even if it has the method 'play()'.
($AnimPlayer as AnimationPlayer).play("walk")

常量

常量代表游戏运行时不可更改的值. 其值在编译时必须已知. 使用 const 关键字即可为常量值赋予名称. 尝试为常量重写赋值会引发错误.

我们建议使用常量来储存不应当更改的值.

const A = 5
const B = Vector2(20, 20)
const C = 10 + 20 # Constant expression.
const D = Vector2(20, 30).x # Constant expression: 20.
const E = [1, 2, 3, 4][0] # Constant expression: 1.
const F = sin(20) # 'sin()' can be used in constant expressions.
const G = x + 20 # Invalid; this is not a constant expression!
const H = A + 20 # Constant expression: 25 (`A` is a constant).

尽管可以从分配的值中推断出常量的类型,但是也可以添加显式的类型说明:

const A: int = 5
const B: Vector2 = Vector2()

分配不兼容类型的值将引发错误.

You can also create constants inside a function, which is useful to name local magic values.

备注

Since objects, arrays and dictionaries are passed by reference, constants are "flat". This means that if you declare a constant array or dictionary, it can still be modified afterwards. They can't be reassigned with another value though.

枚举

枚举基本上是常量的简写, 如果你想为某些常量分配连续整数, 那么枚举非常有用.

enum {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}

# Is the same as:
const TILE_BRICK = 0
const TILE_FLOOR = 1
const TILE_SPIKE = 2
const TILE_TELEPORT = 3

If you pass a name to the enum, it will put all the keys inside a constant Dictionary of that name. This means all constant methods of a dictionary can also be used with a named enum.

重要

Keys in a named enum are not registered as global constants. They should be accessed prefixed by the enum's name (Name.KEY).

enum State {STATE_IDLE, STATE_JUMP = 5, STATE_SHOOT}

# Is the same as:
const State = {STATE_IDLE = 0, STATE_JUMP = 5, STATE_SHOOT = 6}

func _ready():
    # Access values with Name.KEY, prints '5'
    print(State.STATE_JUMP)
    # Use constant dictionary functions
    # prints '["STATE_IDLE", "STATE_JUMP", "STATE_SHOOT"]'
    print(State.keys())

函数

函数总是属于一个 . 变量查找的作用域的优先级是:局部 → 类成员 → 全局. self 变量总是可用的, 并作为访问类成员的选项提供, 但并不总是必需的(与Python不同, 应该将其作为函数的第一个参数传递).

func my_function(a, b):
    print(a)
    print(b)
    return a + b  # Return is optional; without it 'null' is returned.

函数可以在任何时候 return . 默认返回值是 null.

If a function contains only one line of code, it can be written on one line:

func square(a): return a * a

func hello_world(): print("Hello World")

func empty_function(): pass

函数也可以具有参数和返回值的类型声明。可以使用与变量类似的方式添加参数的类型:

func my_function(a: int, b: String):
    pass

如果函数参数具有默认值,则可以推断类型:

func my_function(int_arg := 42, String_arg := "string"):
    pass

可以在参数列表之后使用箭头标记(->)指定函数的返回类型:

func my_int_function() -> int:
    return 0

有返回类型的函数 必须 返回正确的值. 将类型设置为 void 意味着函数不返回任何内容.Void函数可以使用 return 关键字提前返回, 但不能返回任何值.

func void_function() -> void:
    return # Can't return a value.

备注

非void函数必须 总是 返回一个值, 所以如果您的代码有分支语句(例如 if/else 构造), 那么所有可能的路径都必须返回一个值. 例如, 如果在 if 块中有一个 return , 但在 if 块之后没有, 编辑器就会抛出一个错误, 因为如果没有执行这个块, 该函数将没有有效值返回.

引用函数

Functions are first-class items in terms of the Callable object. Referencing a function by name without calling it will automatically generate the proper callable. This can be used to pass functions as arguments.

func map(arr: Array, function: Callable) -> Array:
    var result = []
    for item in arr:
        result.push_back(function.call(item))
    return result

func add1(value: int) -> int:
    return value + 1;

func _ready() -> void:
    var my_array = [1, 2, 3]
    var plus_one = map(my_array, add1)
    print(plus_one) # Prints [2, 3, 4].

备注

Callables must be called with the call method. You cannot use the () operator directly. This behavior is implemented to avoid performance issues on direct function calls.

Lambda functions

Lambda functions allow you to declare functions that do not belong to a class. Instead a Callable object is created and assigned to a variable directly. This can be useful to create Callables to pass around without polluting the class scope.

var lambda = func(x): print(x)
lambda.call(42) # Prints "42"

Lambda functions can be named for debugging purposes:

var lambda = func my_lambda(x):
    print(x)

Lambda functions capture the local environment. Local variables are passed by value, so they won't be updated in the lambda if changed in the local function:

var x = 42
var my_lambda = func(): print(x)
my_lambda.call() # Prints "42"
x = "Hello"
my_lambda.call() # Prints "42"

备注

The values of the outer scope behave like constants. Therefore, if you declare an array or dictionary, it can still be modified afterwards.

静态函数

A function can be declared static. When a function is static, it has no access to the instance member variables or self. A static function has access to static variables. Also static functions are useful to make libraries of helper functions:

static func sum2(a, b):
    return a + b

Lambdas cannot be declared static.

See also Static variables and Static constructor.

语句和控制流程

语句是标准的, 可以是赋值, 函数调用, 控制流结构等(见下面). ; 作为语句分隔符是完全可选的.

Expressions

Expressions are sequences of operators and their operands in orderly fashion. An expression by itself can be a statement too, though only calls are reasonable to use as statements since other expressions don't have side effects.

Expressions return values that can be assigned to valid targets. Operands to some operator can be another expression. An assignment is not an expression and thus does not return any value.

Here are some examples of expressions:

2 + 2 # Binary operation.
-5 # Unary operation.
"okay" if x > 4 else "not okay" # Ternary operation.
x # Identifier representing variable or constant.
x.a # Attribute access.
x[4] # Subscript access.
x > 2 or x < 5 # Comparisons and logic operators.
x == y + 2 # Equality test.
do_something() # Function call.
[1, 2, 3] # Array definition.
{A = 1, B = 2} # Dictionary definition.
preload("res://icon.png") # Preload builtin function.
self # Reference to current instance.

Identifiers, attributes, and subscripts are valid assignment targets. Other expressions cannot be on the left side of an assignment.

if/else/elif

简单的条件是通过使用 if/else/elif 语法创建的. 条件的括号是允许的, 但不是必需的. 考虑到基于制表符的缩进的性质, 可以使用 elif 而不是 else/if 来维持缩进的级别.

if (expression):
    statement(s)
elif (expression):
    statement(s)
else:
    statement(s)

短语句可以写在与条件相同的行上:

if 1 + 1 == 2: return 2 + 2
else:
    var x = 3 + 3
    return x

有时您可能希望基于布尔表达式分配不同的初始值。在这种情况下,三元表达式将派上用场:

var x = (value) if (expression) else (value)
y += 3 if y < 10 else -1

可以通过嵌套三元 if 表达式来处理的超过两种可能性的情况。嵌套时,推荐把三元 if 表达式拆分到多行以保持可读性:

var count = 0

var fruit = (
        "apple" if count == 2
        else "pear" if count == 1
        else "banana" if count == 0
        else "orange"
)
print(fruit)  # banana

# Alternative syntax with backslashes instead of parentheses (for multi-line expressions).
# Less lines required, but harder to refactor.
var fruit_alt = \
        "apple" if count == 2 \
        else "pear" if count == 1 \
        else "banana" if count == 0 \
        else "orange"
print(fruit_alt)  # banana

你可能还想要检查某个值是否包含在某些东西之中。可以通过 if 语句与 in 操作符的组合来实现:

# Check if a letter is in a string.
var text = "abc"
if 'b' in text: print("The string contains b")

# Check if a variable is contained within a node.
if "varName" in get_parent(): print("varName is defined in parent!")

while

Simple loops are created by using while syntax. Loops can be broken using break or continued using continue (which skips to the next iteration of the loop without executing any further code in the current iteration):

while (expression):
    statement(s)

for

要遍历一个范围(如数组或表), 使用 for 循环. 在数组上迭代时, 当前数组元素存储在循环变量中. 在遍历字典时, 键(key) 存储在循环变量中.

for x in [5, 7, 11]:
    statement # Loop iterates 3 times with 'x' as 5, then 7 and finally 11.

var dict = {"a": 0, "b": 1, "c": 2}
for i in dict:
    print(dict[i]) # Prints 0, then 1, then 2.

for i in range(3):
    statement # Similar to [0, 1, 2] but does not allocate an array.

for i in range(1, 3):
    statement # Similar to [1, 2] but does not allocate an array.

for i in range(2, 8, 2):
    statement # Similar to [2, 4, 6] but does not allocate an array.

for i in range(8, 2, -2):
    statement # Similar to [8, 6, 4] but does not allocate an array.

for c in "Hello":
    print(c) # Iterate through all characters in a String, print every letter on new line.

for i in 3:
    statement # Similar to range(3).

for i in 2.2:
    statement # Similar to range(ceil(2.2)).

If you want to assign values on an array as it is being iterated through, it is best to use for i in array.size().

for i in array.size():
        array[i] = "Hello World"

The loop variable is local to the for-loop and assigning to it will not change the value on the array. Objects passed by reference (such as nodes) can still be manipulated by calling methods on the loop variable.

for string in string_array:
    string = "Hello World" # This has no effect

for node in node_array:
    node.add_to_group("Cool_Group") # This has an effect

match

match 语句用于分支程序的执行。它相当于在许多其他语言中出现的 switch 语句,但提供了一些附加功能。

基本语法:

match (expression):
    [pattern](s):
        [block]
    [pattern](s):
        [block]
    [pattern](s):
        [block]

警告

match is more type strict than the == operator. For example 1 will not match 1.0. The only exception is String vs StringName matching: for example, the String "hello" is considered equal to the StringName &"hello".

熟悉 switch 语句的人的速成课程

  1. switch 替换为 match

  2. 删除 case

  3. Remove any breaks.

  4. default 替换为单个下划线。

控制流

The patterns are matched from top to bottom. If a pattern matches, the first corresponding block will be executed. After that, the execution continues below the match statement.

备注

The special continue behavior in match supported in 3.x was removed in Godot 4.0.

有6种模式类型:

  • 常量模式

    常量原语,例如数字和字符串:

    match x:
        1:
            print("We are number one!")
        2:
            print("Two are better than one!")
        "test":
            print("Oh snap! It's a string!")
    
  • 变量模式

    匹配变量/枚举的内容:

    match typeof(x):
        TYPE_FLOAT:
            print("float")
        TYPE_STRING:
            print("text")
        TYPE_ARRAY:
            print("array")
    
  • 通配符模式

    这个模式匹配所有内容. 它被写成一个下划线.

    它可以与其他语言的 switch 语句中的 default 等效:

    match x:
        1:
            print("It's one!")
        2:
            print("It's one times two!")
        _:
            print("It's not 1 or 2. I don't care to be honest.")
    
  • 绑定模式

    绑定模式引入了一个新变量。与通配符模式类似,它匹配所有内容——并为该值提供一个名称。它在数组和字典模式中特别有用:

    match x:
        1:
            print("It's one!")
        2:
            print("It's one times two!")
        var new_var:
            print("It's not 1 or 2, it's ", new_var)
    
  • 数组模式

    匹配一个数组. 数组模式的每个元素本身都是模式, 因此您可以嵌套它们.

    首先测试数组的长度, 它的大小必须与模式相同, 否则模式不匹配.

    开放式数组 : 通过使最后一个子模式为 .. , 可以使数组大于模式.

    每个子模式都必须用逗号分隔.

    match x:
        []:
            print("Empty array")
        [1, 3, "test", null]:
            print("Very specific array")
        [var start, _, "test"]:
            print("First element is ", start, ", and the last is \"test\"")
        [42, ..]:
            print("Open ended array")
    
  • 字典模式

    工作方式与数组模式相同. 每个键必须是一个常量模式.

    首先要测试字典的大小, 它的大小必须与模式相同, 否则模式不匹配.

    开放式字典 : 通过将最后一个子字样改为 .. , 使字典可以比模式大.

    每个子模式都必须用逗号分隔.

    如果不指定值, 则仅检查键的存在.

    值模式与键模式之间以 : 分隔.

    match x:
        {}:
            print("Empty dict")
        {"name": "Dennis"}:
            print("The name is Dennis")
        {"name": "Dennis", "age": var age}:
            print("Dennis is ", age, " years old.")
        {"name", "age"}:
            print("Has a name and an age, but it's not Dennis :(")
        {"key": "godotisawesome", ..}:
            print("I only checked for one entry and ignored the rest")
    
  • 多重模式

    您还可以指定由逗号分隔的多重模式. 这些模式不允许包含任何绑定.

    match x:
        1, 2, 3:
            print("It's 1 - 3")
        "Sword", "Splash potion", "Fist":
            print("Yep, you've taken damage")
    

默认情况下,所有脚本文件都是未命名的类。在这种情况下,只能使用文件的路径引用它们,使用相对路径或绝对路径。例如,如果您将脚本文件命名为 character.gd

# Inherit from 'character.gd'.

extends "res://path/to/character.gd"

# Load character.gd and create a new node instance from it.

var Character = load("res://path/to/character.gd")
var character_node = Character.new()

注册具名类

You can give your class a name to register it as a new type in Godot's editor. For that, you use the class_name keyword. You can optionally use the @icon annotation with a path to an image, to use it as an icon. Your class will then appear with its new icon in the editor:

# item.gd

@icon("res://interface/icons/item.png")
class_name Item
extends Node
../../../_images/class_name_editor_register_example.png

这是一个类文件示例:

# Saved as a file named 'character.gd'.

class_name Character


var health = 5


func print_health():
    print(health)


func print_this_script_three_times():
    print(get_script())
    print(ResourceLoader.load("res://character.gd"))
    print(Character)

If you want to use extends too, you can keep both on the same line:

class_name MyNode extends Node

备注

Godot initializes non-static variables every time you create an instance, and this includes arrays and dictionaries. This is in the spirit of thread safety, since scripts can be initialized in separate threads without the user knowing.

继承

类(以文件形式保存)可以继承自:

  • 全局类。

  • 另一个类文件。

  • 另一个类文件中的内部类。

不允许多重继承。

继承使用 extends 关键字:

# Inherit/extend a globally available class.
extends SomeClass

# Inherit/extend a named class file.
extends "somefile.gd"

# Inherit/extend an inner class in another file.
extends "somefile.gd".SomeInnerClass

备注

If inheritance is not explicitly defined, the class will default to inheriting RefCounted.

要检查给定的实例是否从给定的类继承,可以使用 is 关键字:

# Cache the enemy class.
const Enemy = preload("enemy.gd")

# [...]

# Use 'is' to check inheritance.
if entity is Enemy:
    entity.apply_damage()

To call a function in a super class (i.e. one extend-ed in your current class), use the super keyword:

super(args)

This is especially useful because functions in extending classes replace functions with the same name in their super classes. If you still want to call them, you can use super:

func some_func(x):
    super(x) # Calls the same function on the super class.

If you need to call a different function from the super class, you can specify the function name with the attribute operator:

func overriding():
    return 0 # This overrides the method in the base class.

func dont_override():
    return super.overriding() # This calls the method as defined in the base class.

警告

One of the common misconceptions is trying to override non-virtual engine methods such as get_class(), queue_free(), etc. This is not supported for technical reasons.

In Godot 3, you can shadow engine methods in GDScript, and it will work if you call this method in GDScript. However, the engine will not execute your code if the method is called inside the engine on some event.

In Godot 4, even shadowing may not always work, as GDScript optimizes native method calls. Therefore, we added the NATIVE_METHOD_OVERRIDE warning, which is treated as an error by default. We strongly advise against disabling or ignoring the warning.

Note that this does not apply to virtual methods such as _ready(), _process() and others (marked with the virtual qualifier in the documentation and the names start with an underscore). These methods are specifically for customizing engine behavior and can be overridden in GDScript. Signals and notifications can also be useful for these purposes.

类的构造函数

The class constructor, called on class instantiation, is named _init. If you want to call the base class constructor, you can also use the super syntax. Note that every class has an implicit constructor that it's always called (defining the default values of class variables). super is used to call the explicit constructor:

func _init(arg):
   super("some_default", arg) # Call the custom base constructor.

通过示例可以更好地说明这一点。考虑这种情况:

# state.gd (inherited class).
var entity = null
var message = null


func _init(e=null):
    entity = e


func enter(m):
    message = m


# idle.gd (inheriting class).
extends "state.gd"


func _init(e=null, m=null):
    super(e)
    # Do something with 'e'.
    message = m

这里有几件事要记住:

  1. If the inherited class (state.gd) defines a _init constructor that takes arguments (e in this case), then the inheriting class (idle.gd) must define _init as well and pass appropriate parameters to _init from state.gd.

  2. idle.gd can have a different number of arguments than the base class state.gd.

  3. In the example above, e passed to the state.gd constructor is the same e passed in to idle.gd.

  4. If idle.gd's _init constructor takes 0 arguments, it still needs to pass some value to the state.gd base class, even if it does nothing. This brings us to the fact that you can pass expressions to the base constructor as well, not just variables, e.g.:

    # idle.gd
    
    func _init():
        super(5)
    

Static constructor

A static constructor is a static function _static_init that is called automatically when the class is loaded, after the static variables have been initialized:

static var my_static_var = 1

static func _static_init():
    my_static_var = 2

A static constructor cannot take arguments and must not return any value.

内部类

类文件可以包含内部类。内部类使用 class 关键字定义。它们使用 类名.new() 函数实例化。

# Inside a class file.

# An inner class in this class file.
class SomeInnerClass:
    var a = 5


    func print_value_of_a():
        print(a)


# This is the constructor of the class file's main class.
func _init():
    var c = SomeInnerClass.new()
    c.print_value_of_a()

类作为资源

存储为文件的类被视为 Resource。必须从磁盘加载它们,才能在其他类中访问它们。这可以使用 loadpreload 函数来完成(后述)。一个加载的类资源的实例化是通过调用类对象上的 new 函数来完成的:

# Load the class resource when calling load().
var MyClass = load("myclass.gd")

# Preload the class only once at compile time.
const MyClass = preload("myclass.gd")


func _init():
    var a = MyClass.new()
    a.some_function()

导出

备注

有关导出的文档已移至 GDScript 导出

Properties (setters and getters)

Sometimes, you want a class' member variable to do more than just hold data and actually perform some validation or computation whenever its value changes. It may also be desired to encapsulate its access in some way.

For this, GDScript provides a special syntax to define properties using the set and get keywords after a variable declaration. Then you can define a code block that will be executed when the variable is accessed or assigned.

Example:

var milliseconds: int = 0
var seconds: int:
    get:
        return milliseconds / 1000
    set(value):
        milliseconds = value * 1000

Using the variable's name to set it inside its own setter or to get it inside its own getter will directly access the underlying member, so it won't generate infinite recursion and saves you from explicitly declaring another variable:

signal changed(new_value)
var warns_when_changed = "some value":
    get:
        return warns_when_changed
    set(value):
        changed.emit(value)
        warns_when_changed = value

This backing member variable is not created if you don't use it.

备注

Unlike setget in previous Godot versions, the properties setter and getter are always called, even when accessed inside the same class (with or without prefixing with self.). This makes the behavior consistent. If you need direct access to the value, use another variable for direct access and make the property code use that name.

In case you want to split the code from the variable declaration or you need to share the code across multiple properties, you can use a different notation to use existing class functions:

var my_prop:
    get = get_my_prop, set = set_my_prop

This can also be done in the same line.

工具模式

By default, scripts don't run inside the editor and only the exported properties can be changed. In some cases, it is desired that they do run inside the editor (as long as they don't execute game code or manually avoid doing so). For this, the @tool annotation exists and must be placed at the top of the file:

@tool
extends Button

func _ready():
    print("Hello")

详情见 在编辑器中运行代码

警告

在工具脚本(尤其是脚本的所有者本身)中使用 queue_free()free() 释放节点时要谨慎。因为工具脚本是在编辑器中运行代码的,滥用可能导致编辑器崩溃。

内存管理

Godot implements reference counting to free certain instances that are no longer used, instead of a garbage collector, or requiring purely manual management. Any instance of the RefCounted class (or any class that inherits it, such as Resource) will be freed automatically when no longer in use. For an instance of any class that is not a RefCounted (such as Node or the base Object type), it will remain in memory until it is deleted with free() (or queue_free() for Nodes).

备注

If a Node is deleted via free() or queue_free(), all of its children will also recursively be deleted.

To avoid reference cycles that can't be freed, a WeakRef function is provided for creating weak references, which allow access to the object without preventing a RefCounted from freeing. Here is an example:

extends Node

var my_file_ref

func _ready():
    var f = FileAccess.open("user://example_file.json", FileAccess.READ)
    my_file_ref = weakref(f)
    # the FileAccess class inherits RefCounted, so it will be freed when not in use

    # the WeakRef will not prevent f from being freed when other_node is finished
    other_node.use_file(f)

func _this_is_called_later():
    var my_file = my_file_ref.get_ref()
    if my_file:
        my_file.close()

或者,当不使用引用时,可以使用 is_instance_valid(instance) 来检查对象是否已被释放。

信号

信号是从对象发出消息的工具,其他对象也可以对此做出反应。要为一个类创建自定义信号,请使用 signal 关键字。

extends Node


# A signal named health_depleted.
signal health_depleted

备注

信号是一种回调机制。它们还充当观察者的角色,这是一种常见的编程模式。有关更多信息,请阅读《游戏编程模式》电子书中的观察者教程

You can connect these signals to methods the same way you connect built-in signals of nodes like Button or RigidBody3D.

In the example below, we connect the health_depleted signal from a Character node to a Game node. When the Character node emits the signal, the game node's _on_character_health_depleted is called:

# game.gd

func _ready():
    var character_node = get_node('Character')
    character_node.health_depleted.connect(_on_character_health_depleted)


func _on_character_health_depleted():
    get_tree().reload_current_scene()

您可以发出任意数量的参数附带一个信号。

这是一个有用的示例。假设我们希望屏幕上的生命条能够通过动画对健康值做出反应,但我们希望在场景树中将用户界面与游戏角色保持独立。

In our character.gd script, we define a health_changed signal and emit it with Signal.emit(), and from a Game node higher up our scene tree, we connect it to the Lifebar using the Signal.connect() method:

# character.gd

...
signal health_changed


func take_damage(amount):
    var old_health = health
    health -= amount

    # We emit the health_changed signal every time the
    # character takes damage.
    health_changed.emit(old_health, health)
...
# lifebar.gd

# Here, we define a function to use as a callback when the
# character's health_changed signal is emitted.

...
func _on_Character_health_changed(old_value, new_value):
    if old_value > new_value:
        progress_bar.modulate = Color.RED
    else:
        progress_bar.modulate = Color.GREEN

    # Imagine that `animate` is a user-defined function that animates the
    # bar filling up or emptying itself.
    progress_bar.animate(old_value, new_value)
...

Game 节点中,我们同时获得 CharacterLifebar 节点,然后将发出信号的 Character 连接到接收器,在本例中为 Lifebar 节点。

# game.gd

func _ready():
    var character_node = get_node('Character')
    var lifebar_node = get_node('UserInterface/Lifebar')

    character_node.health_changed.connect(lifebar_node._on_Character_health_changed)

这样 Lifebar 就能够对健康值做出反应,无需将其耦合到 Character 节点。

您可以在信号的定义后的括号中写上可选的参数名称:

# Defining a signal that forwards two arguments.
signal health_changed(old_value, new_value)

这些参数显示在编辑器的节点停靠面板中,Godot可以使用它们为您生成回调函数. 但是, 发出信号时仍然可以发出任意数量的参数;由您来发出正确的值.

../../../_images/gdscript_basics_signals_node_tab_1.png

GDScript可以将值数组绑定到信号和方法之间的连接. 发出信号时, 回调方法将接收绑定值. 这些绑定参数对于每个连接都是唯一的, 并且值将保持不变.

如果发出的信号本身不能使您访问所需的所有数据, 则可以使用此值数组将额外的常量信息添加到连接.

以上面的示例为基础,假设我们要在屏幕上显示每个角色遭受伤害的日志,例如 Player1 遭受了 22 伤害。health_changed 信号没有给我们提供受到伤害的角色的名称。因此,当我们将信号连接到游戏终端中时,可以在绑定数组参数中添加角色的名称:

# game.gd

func _ready():
    var character_node = get_node('Character')
    var battle_log_node = get_node('UserInterface/BattleLog')

    character_node.health_changed.connect(battle_log_node._on_Character_health_changed, [character_node.name])

我们的 BattleLog 节点接收绑定数组中的每个元素作为一个额外的参数:

# battle_log.gd

func _on_Character_health_changed(old_value, new_value, character_name):
    if not new_value <= old_value:
        return

    var damage = old_value - new_value
    label.text += character_name + " took " + str(damage) + " damage."

Awaiting for signals or coroutines

The await keyword can be used to create coroutines which wait until a signal is emitted before continuing execution. Using the await keyword with a signal or a call to a function that is also a coroutine will immediately return the control to the caller. When the signal is emitted (or the called coroutine finishes), it will resume execution from the point on where it stopped.

For example, to stop execution until the user presses a button, you can do something like this:

func wait_confirmation():
    print("Prompting user")
    await $Button.button_up # Waits for the button_up signal from Button node.
    print("User confirmed")
    return true

In this case, the wait_confirmation becomes a coroutine, which means that the caller also needs to await for it:

func request_confirmation():
    print("Will ask the user")
    var confirmed = await wait_confirmation()
    if confirmed:
        print("User confirmed")
    else:
        print("User cancelled")

Note that requesting a coroutine's return value without await will trigger an error:

func wrong():
    var confirmed = wait_confirmation() # Will give an error.

However, if you don't depend on the result, you can just call it asynchronously, which won't stop execution and won't make the current function a coroutine:

func okay():
    wait_confirmation()
    print("This will be printed immediately, before the user press the button.")

If you use await with an expression that isn't a signal nor a coroutine, the value will be returned immediately and the function won't give the control back to the caller:

func no_wait():
    var x = await get_five()
    print("This doesn't make this function a coroutine.")

func get_five():
    return 5

This also means that returning a signal from a function that isn't a coroutine will make the caller await on that signal:

func get_signal():
    return $Button.button_up

func wait_button():
    await get_signal()
    print("Button was pressed")

备注

Unlike yield in previous Godot versions, you cannot obtain the function state object. This is done to ensure type safety. With this type safety in place, a function cannot say that it returns an int while it actually returns a function state object during runtime.

Assert 关键字

assert 关键字可用于检查调试版本中的条件. 在非调试版本中, 这些断言将被忽略. 这意味着在发布模式下导出的项目中不会评估作为参数传递的表达式. 因此, 断言必须 不能 包含具有副作用的表达式. 否则, 脚本的行为将取决于项目是否在调试版本中运行.

# Check that 'i' is 0. If 'i' is not 0, an assertion error will occur.
assert(i == 0)

从编辑器运行项目时, 如果发生断言错误, 该项目将被暂停.

You can optionally pass a custom error message to be shown if the assertion fails:

assert(enemy_power < 256, "Enemy is too powerful!")