GDScript 导出

导出简介

在 Godot 中可以导出类成员。这意味着它们的值会与它们所附加的资源(例如场景)一起保存。它们也可以在属性编辑器中进行编辑。导出使用关键字 export 来完成:

extends Button

export var number = 5 # Value will be saved and visible in the property editor.

导出的变量必须使用常量表达式初始化,或者用 export 关键字参数的形式提供导出提示(请参见下面的示例部分)。

导出成员变量的基本好处之一是使它们在编辑器中可见并可编辑. 这样, 美术师和游戏设计师可以修改值, 这些值以后会影响程序的运行方式. 为此, 提供了一种特殊的导出语法.

备注

C# 等其他语言也可以进行属性的导出。不同的语言有不同的语法。

示例

# If the exported value assigns a constant or constant expression,
# the type will be inferred and used in the editor.

export var number = 5

# Export can take a basic data type as an argument, which will be
# used in the editor.

export(int) var number

# Export can also take a resource type to use as a hint.

export(Texture) var character_face
export(PackedScene) var scene_file
# There are many resource types that can be used this way, try e.g.
# the following to list them:
export(Resource) var resource

# Integers and strings hint enumerated values.

# Editor will enumerate as 0, 1 and 2.
export(int, "Warrior", "Magician", "Thief") var character_class
# Editor will enumerate with string names.
export(String, "Rebecca", "Mary", "Leah") var character_name

# Named enum values

# Editor will enumerate as THING_1, THING_2, ANOTHER_THING.
enum NamedEnum {THING_1, THING_2, ANOTHER_THING = -1}
export(NamedEnum) var x

# Strings as paths

# String is a path to a file.
export(String, FILE) var f
# String is a path to a directory.
export(String, DIR) var f
# String is a path to a file, custom filter provided as hint.
export(String, FILE, "*.txt") var f

# Using paths in the global filesystem is also possible,
# but only in scripts in "tool" mode.

# String is a path to a PNG file in the global filesystem.
export(String, FILE, GLOBAL, "*.png") var tool_image
# String is a path to a directory in the global filesystem.
export(String, DIR, GLOBAL) var tool_dir

# The MULTILINE setting tells the editor to show a large input
# field for editing over multiple lines.
export(String, MULTILINE) var text

# Limiting editor input ranges

# Allow integer values from 0 to 20.
export(int, 20) var i
# Allow integer values from -10 to 20.
export(int, -10, 20) var j
# Allow floats from -10 to 20 and snap the value to multiples of 0.2.
export(float, -10, 20, 0.2) var k
# Allow values 'y = exp(x)' where 'y' varies between 100 and 1000
# while snapping to steps of 20. The editor will present a
# slider for easily editing the value.
export(float, EXP, 100, 1000, 20) var l

# Floats with easing hint

# Display a visual representation of the 'ease()' function
# when editing.
export(float, EASE) var transition_speed

# Colors

# Color given as red-green-blue value (alpha will always be 1).
export(Color, RGB) var col
# Color given as red-green-blue-alpha value.
export(Color, RGBA) var col

# Nodes

# Another node in the scene can be exported as a NodePath.
export(NodePath) var node_path
# Do take note that the node itself isn't being exported -
# there is one more step to call the true node:
onready var node = get_node(node_path)

# Resources

export(Resource) var resource
# In the Inspector, you can then drag and drop a resource file
# from the FileSystem dock into the variable slot.

# Opening the inspector dropdown may result in an
# extremely long list of possible classes to create, however.
# Therefore, if you specify an extension of Resource such as:
export(AnimationNode) var resource
# The drop-down menu will be limited to AnimationNode and all
# its inherited classes.

必须注意, 即使在编辑器中未运行脚本, 导出的属性仍可编辑. 可以与 使用工具模式的脚本 结合使用.

导出位标志

用作位标志的整数可以在一个属性中存储多个 true/ false(布尔)值。通过使用导出提示 int, FLAGS, ...,可以在编辑器中设置它们:

# Set any of the given flags from the editor.
export(int, FLAGS, "Fire", "Water", "Earth", "Wind") var spell_elements = 0

你必须为每个标志提供一个字符串描述。在这个例子中,Fire 的值是 1,Water 的值是 2,Earth 的值是 4,Wind 对应的值是 8。通常,应相应地定义常量(例如 const ELEMENT_WIND = 8 等等)。

也可以为项目设置中定义的物理层和渲染层提供导出提示:

export(int, LAYERS_2D_PHYSICS) var layers_2d_physics
export(int, LAYERS_2D_RENDER) var layers_2d_render
export(int, LAYERS_3D_PHYSICS) var layers_3d_physics
export(int, LAYERS_3D_RENDER) var layers_3d_render

使用位标志需要对位操作有一定的了解. 如果有疑问, 请使用布尔变量代替.

导出数组

导出的数组可以具有初始化器, 但是它们必须是常量表达式.

如果导出的数组指定了从 Resource 继承的类型,则可以通过一次从文件系统面板中拖放多个文件来在检查器中设置数组值。

# Default value must be a constant expression.

export var a = [1, 2, 3]

# Exported arrays can specify type (using the same hints as before).

export(Array, int) var ints = [1, 2, 3]
export(Array, int, "Red", "Green", "Blue") var enums = [2, 1, 0]
export(Array, Array, float) var two_dimensional = [[1.0, 2.0], [3.0, 4.0]]

# You can omit the default value, but then it would be null if not assigned.

export(Array) var b
export(Array, PackedScene) var scenes

# Arrays with specified types which inherit from resource can be set by
# drag-and-dropping multiple files from the FileSystem dock.

export(Array, Texture) var textures
export(Array, PackedScene) var scenes

# Typed arrays also work, only initialized empty:

export var vector3s = PoolVector3Array()
export var strings = PoolStringArray()

# Default value can include run-time values, but can't
# be exported.

var c = [a, 2, 3]

从工具脚本设置导出变量

工具模式 下的脚本中更改一个导出变量的值时,检查器中对应的值不会自动更新。要更新它,请在设置导出变量的值之后,调用 property_list_changed_notify()

高级导出

为了避免不必要的复杂设计,不是所有导出类型都在语言层面上提供。下面将说明一些能用底层 API 实现的,较为常见的导出方法。

在进一步阅读前,你需要熟悉属性的运作方式以及它们是如何通过 _set()_get()_get_property_list() 方法进行定制的。详情可参阅 从对象访问数据或逻辑

参见

要在 C++ 中用上述方法绑定属性,请参阅 使用 _set/_get/_get_property_list 绑定属性

警告

脚本必须在 tool 模式运行,上述方法才能在编辑器内运行。

属性

为了更好地理解后续章节,你应该理解如何使用高级导出来制作属性。

func _get_property_list():
    var properties = []
    # Same as "export(int) var my_property"
    properties.append({
        name = "my_property",
        type = TYPE_INT
    })
    return properties
  • 检查器会调用 _get_property_list() 函数。你可以对它进行覆盖,进行高级导出。要让这个函数正常工作,你必须返回一个包含属性内容的 Array

  • name 是该属性的名称

  • type 是该属性的类型,使用 Variant.Type

备注

浮点数类型 floatVariant.Type 枚举中叫作实数(TYPE_REAL)。

将变量与属性关联

要将变量与属性关联起来(让属性的值可以在脚本中使用),你需要创建一个与该属性同名的变量,否则就需要覆盖 _set()_get() 方法。将变量与属性关联后,你还可以给它设置默认状态。

# This variable is determined by the function below.
# This variable acts just like a regular gdscript export.
var my_property = 5

func _get_property_list():
    var properties = []
    # Same as "export(int) var my_property"
    properties.append({
        name = "my_property",
        type = TYPE_INT
    })
    return properties

为属性添加默认值

要为高级导出定义默认值,你需要覆盖 property_can_revert()property_get_revert() 方法。

  • property_can_revert() 方法接受属性的名称,必须在该属性能够复原时返回 true。这样就可以启用检查器中该属性旁的“恢复”按钮。

  • property_get_revert() 方法接受属性的名称,必须返回该属性的默认值。

func _get_property_list():
    var properties = []
    properties.append({
        name = "my_property",
        type = TYPE_INT
    })
    return properties

func property_can_revert(property):
    if property == "my_property":
        return true
    return false

func property_get_revert(property):
    if property == "my_property":
        return 5

添加脚本分类

为了在视觉上更好区分各个属性,可以将特殊的脚本分类作为分隔线嵌入检查器。Script Variables 就是一种内建分类。

func _get_property_list():
    var properties = []
    properties.append({
        name = "Debug",
        type = TYPE_NIL,
        usage = PROPERTY_USAGE_CATEGORY | PROPERTY_USAGE_SCRIPT_VARIABLE
    })

    # Example of adding a property to the script category
    properties.append({
        name = "Logging_Enabled",
        type = TYPE_BOOL
    })
    return properties
  • name 是要加入检查器中的分类的名字;

  • 定义分类后,添加的所有属性都会成为该分类的一部分。

  • PROPERTY_USAGE_CATEGORY 表明了该属性应被视为一个脚本分类,因此可以忽略 TYPE_NIL 这个类型,因为它其实并没有被脚本逻辑所处理。不过你还是必须在这儿定义它。

对属性进行分组

名称类似的属性可以合为一组。

func _get_property_list():
    var properties = []
    properties.append({
        name = "Rotate",
        type = TYPE_NIL,
        hint_string = "rotate_",
        usage = PROPERTY_USAGE_GROUP | PROPERTY_USAGE_SCRIPT_VARIABLE
    })

    # Example of adding to the group
    properties.append({
        name = "rotate_speed",
        type = TYPE_REAL
    })

    # This property won't get added to the group
    # due to not having the "rotate_" prefix.
    properties.append({
        name = "trail_color",
        type = TYPE_COLOR
    })
    return properties
  • name 是包含了一组属性的可折叠群组的名称;

  • 在分组属性之后添加的属性,如果带有相同前缀(由 hint_string 决定)就会被缩短。例如,这里的 rotate_speed 会被缩短为 speed。不过,movement_speed 不会成为该组的一部分,也不会被缩短。

  • PROPERTY_USAGE_GROUP 表明了该属性应被视为一个脚本分类, 因此可以忽略 TYPE_NIL 这个类型, 因为它其实并没有被脚本逻辑所处理. 但无论如何, 你还是要在这儿定义它.