Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

资源

节点和资源

在本教程之前, 我们重点研究Godot中的 Node 类, 因为它是你用来编码行为的类, 并且引擎的大多数功能都依赖于该类. 还有另一个同样重要的数据类型: Resource.

节点 为你提供功能: 它们绘制精灵, 3D模型, 模拟物理, 排列用户界面等. 资源数据容器 . 它们自己不能做任何事情: 而是, 节点使用资源中包含的数据.

Godot 保存到磁盘、从磁盘读取的都是资源。资源可以是场景(.tscn.scn 文件)、图像、脚本……以下是一些 Resource 的示例:

当引擎从磁盘加载资源时, 它只加载一次 . 如果该资源的副本已在内存中, 则每次尝试再次加载该资源将返回相同的副本. 由于资源只包含数据, 因此无需复制它们.

每个对象(无论是节点还是资源)都可以导出属性. 属性有很多类型, 例如String, integer, Vector2等, 并且任何这些类型都可以成为资源. 这意味着节点和资源都可以包含资源以作为属性:

../../_images/nodes_resources.webp

外部与内置

有两种保存资源的方法. 它们是:

  1. 外部 , 对于场景, 作为单独文件保存在磁盘上.

  2. 内置,保存在它们所附加的 .tscn.scn 文件内。

To be more specific, here's a Texture2D in a Sprite2D node:

../../_images/spriteprop.webp

Clicking the resource preview allows us to view the resource's properties.

../../_images/resourcerobi.webp

Path 属性告诉我们资源来自何处. 在这里, 它来自一个叫 robi.png 的PNG图像. 当资源来自这样的文件时, 它属于外部资源. 如果你去掉这个路径或此路径为空, 则它将成为内置资源.

保存场景时, 将在内置资源和外部资源之间进行切换. 在上面的示例中, 如果删除路径 "res://robi.png" 并保存,Godot会将图像保存在 .tscn 场景文件中.

备注

即使你保存一个内置资源, 当多次实例化一个场景时, 引擎也只会加载该场景的一个副本.

从代码中加载资源

有两种方法可以从代码加载资源. 首先, 你可以随时使用 load() 函数:

func _ready():
    # Godot loads the Resource when it reads this very line.
    var imported_resource = load("res://robi.png")
    $sprite.texture = imported_resource

You can also preload resources. Unlike load, this function will read the file from disk and load it at compile-time. As a result, you cannot call preload with a variable path: you need to use a constant string.

func _ready():
    # Godot loads the resource at compile-time
    var imported_resource = preload("res://robi.png")
    get_node("sprite").texture = imported_resource

加载场景

Scenes are also resources, but there is a catch. Scenes saved to disk are resources of type PackedScene. The scene is packed inside a Resource.

To get an instance of the scene, you have to use the PackedScene.instantiate() method.

func _on_shoot():
        var bullet = preload("res://bullet.tscn").instantiate()
        add_child(bullet)

此方法在场景的层次结构中创建节点, 对其进行配置, 然后返回场景的根节点. 然后, 你可以将其添加为任何其他节点的子级.

The approach has several advantages. As the PackedScene.instantiate() function is fast, you can create new enemies, bullets, effects, etc. without having to load them again from disk each time. Remember that, as always, images, meshes, etc. are all shared between the scene instances.

释放资源

When a Resource is no longer in use, it will automatically free itself. Since, in most cases, Resources are contained in Nodes, when you free a node, the engine frees all the resources it owns as well if no other node uses them.

创建自己的资源

像Godot中的任何Object一样, 用户也可以编写资源脚本. 资源脚本继承了object类属性和序列化文本或二进制数据( *.tres , *.res )之间自由转换的能力. 它们还从 Reference 类型继承引用计数内存管理.

This comes with many distinct advantages over alternative data structures, such as JSON, CSV, or custom TXT files. Users can only import these assets as a Dictionary (JSON) or as a FileAccess to parse. What sets Resources apart is their inheritance of Object, RefCounted, and Resource features:

  • 它们可以定义常量, 因此不需要其他数据字段或对象中的常量.

  • 它们可以定义方法, 包括属性的 setter/getter 方法. 这允许对基础数据进行抽象和封装. 如果资源脚本的结构需要更改, 则使用资源的游戏则不必更改.

  • 它们可以定义信号, 因此 Resources 可以触发对所管理数据更改的响应.

  • 它们具有已定义的属性, 因此用户知道其数据将100%存在.

  • 资源自动序列化和反序列化是一个Godot引擎的内置功能. 用户无需实现自定义逻辑即可导入/导出资源文件的数据.

  • 资源甚至可以递归地序列化子资源, 这意味着用户可以设计更复杂的数据结构.

  • 用户可以将资源保存为版本控制友好的文本文件(*.tres). 导出游戏后,Godot将资源文件序列化为二进制文件(*.res), 以提高速度和压缩率.

  • Godot 引擎的检查器开箱即用地渲染和编辑资源文件。这样,用户通常不需要实现自定义逻辑即可可视化或编辑其数据。为此,请在文件系统面板中双击资源文件,或在检查器中点击文件夹图标,然后在对话框中打开该文件。

  • 它们可以扩展除基本 Resource 之外的其他资源类型。

Godot 可以轻松地在检查器面板中创建自定义 Resource。

  1. 在检查器面板中创建一个普通的 Resource 对象。只要是扩展自 Resource 的类型,你的脚本就可以去扩展。

  2. 将检查器中的 script 属性设置为你的脚本。

现在,检查器将显示 Resource 脚本的自定义属性。如果编辑这些值并保存资源,则检查器也会序列化自定义属性!要从检查器中保存资源,请点击检查器的工具菜单(右上角),然后选择“保存”或“另存为...”。

如果脚本的语言支持脚本类,则可以简化该过程。仅为脚本定义名称会将其添加到“检查器”的创建对话框。这会将脚本自动添加到你创建的 Resource 对象中。

Let's see some examples. Create a Resource and name it bot_stats. It should appear in your file tab with the full name bot_stats.tres. Without a script, it's useless, so let's add some data and logic! Attach a script to it named bot_stats.gd (or just create a new script, and then drag it to it).

extends Resource

@export var health: int
@export var sub_resource: Resource
@export var strings: PackedStringArray

# Make sure that every parameter has a default value.
# Otherwise, there will be problems with creating and editing
# your resource via the inspector.
func _init(p_health = 0, p_sub_resource = null, p_strings = []):
    health = p_health
    sub_resource = p_sub_resource
    strings = p_strings

Now, create a CharacterBody3D, name it Bot, and add the following script to it:

extends CharacterBody3D

@export var stats: Resource

func _ready():
    # Uses an implicit, duck-typed interface for any 'health'-compatible resources.
    if stats:
        stats.health = 10
        print(stats.health)
        # Prints "10"

Now, select the CharacterBody3D node which we named bot, and drag&drop the bot_stats.tres resource onto the Inspector. It should print 10! Obviously, this setup can be used for more advanced features than this, but as long you really understand how it all worked, you should figure out everything else related to Resources.

备注

资源脚本类似于 Unity 的 ScriptableObject。检查器为自定义资源提供内置支持。如果需要的话,用户甚至可以设计自己的基于 Control 控件的工具脚本,并将它们与一个 EditorPlugin 结合起来,以为他们的数据创建自定义的可视化和编辑器。

Unreal Engine's DataTables and CurveTables are also easy to recreate with Resource scripts. DataTables are a String mapped to a custom struct, similar to a Dictionary mapping a String to a secondary custom Resource script.

# bot_stats_table.gd
extends Resource

const BotStats = preload("bot_stats.gd")

var data = {
    "GodotBot": BotStats.new(10), # Creates instance with 10 health.
    "DifferentBot": BotStats.new(20) # A different one with 20 health.
}

func _init():
    print(data)

除了内联 Dictionary 值之外,还可以选择:

  1. 从电子表格导入值表并生成这些键值对。

  2. 在编辑器中设计可视化方法,创建一个简单的插件,在你打开这些类型的 Resource 时,将其添加到检查器中。

CurveTable 是相同的东西,除了映射到一个浮点值数组或一个 Curve/ Curve2D 资源对象之外。

警告

请注意,资源文件(*.tres/*.res)将在文件中存储它们使用的脚本的路径。加载后,它们将获取并加载此脚本作为其类型的扩展。这意味着尝试指定一个子类,即脚本的内部类(例如在 GDScript 中使用 class 关键字)将不起作用。Godot 将无法正确序列化脚本子类上的自定义属性。

在下面的示例中,Godot 将加载 Node 脚本,并看到它没有扩展 Resource,然后判断脚本由于类型不兼容而无法为 Resource 对象加载。

extends Node

class MyResource:
    extends Resource
    @export var value = 5

func _ready():
    var my_res = MyResource.new()

    # This will NOT serialize the 'value' property.
    ResourceSaver.save(my_res, "res://my_res.tres")