Godot中的queue_free()和reload_current_scene()函数

17 Mar 2025 | 4 分钟阅读

queue_free() 是在帧结束时安全地销毁节点并将其从树中删除的快捷方式。 如果我们已经有一个树外的节点,它很有用。

例如

remove_child()add_child() 的反义词。 它从场景树中删除节点。 它不会删除节点,因此我们可以将其添加为另一个节点的子节点,

free() 是从内存中删除节点的方法。 但是,这样做并不总是安全的。 如果我们在其他节点可能仍在处理节点时删除一个节点。

queue_free() 函数会告诉引擎,"在安全的时候删除此节点。"

使用场景管理器重新加载当前场景。 我们需要帮助脚本以 重新加载 当前场景。

打开Godot引擎

queue_free() and reload_current_scene() functions in Godot

打开脚本选项卡

queue_free() and reload_current_scene() functions in Godot

我们从提示数组中得到这个条目。 错误告诉我们索引 5th 我们有索引 1, 2, 3, 4 在那里。 我们正在寻找 5th 数组。 数组数组中没有 5th 值。 因此我们需要一些逻辑,我们想继续添加内容,或者我们也可以更改功能。 我们可以做很多事情。 首先,我们必须确保在讲完故事后,让我们摆脱枪支,给我们完全的台词,不要让玩家输入任何内容。 我们将把它从游戏中移除。 我们不会在这里编写代码,而是创建一个名为 End game 的新函数。

示例

输出

queue_free() and reload_current_scene() functions in Godot
queue_free() and reload_current_scene() functions in Godot
queue_free() and reload_current_scene() functions in Godot

在这里,当故事完成后,文本框会自动 消失

queue_free() and reload_current_scene() functions in Godot

在这里,我们可以编写 PlayerText.hide()PlayerText.visible = false 这些函数用于在我们的故事完成后,文本框将从输出面板中隐藏。 我们也可以在最后使用,但是 PlayerText.show()PlayerText.visible=true 用于在故事完成后隐藏文本框。 因为它们都以相同的方式工作。 我们也可以用 PlayerText.hide() 代替 PlayerText.visible=falsePlayerText.show() 代替 PlayerText.visible=true。

我们可以通过单击并按住其上的 control (ctrl) 按钮来查看 get_tree() 文档或任何函数文档。

我们正在在最后进行按钮对齐。

queue_free() and reload_current_scene() functions in Godot

示例

输出

queue_free() and reload_current_scene() functions in Godot
queue_free() and reload_current_scene() functions in Godot
queue_free() and reload_current_scene() functions in Godot
queue_free() and reload_current_scene() functions in Godot

当故事结束后,文本框 会消失。

queue_free() and reload_current_scene() functions in Godot

当我们点击 按钮 时,文字又出现了!

我们也可以从这里开始一个新故事。

queue_free() and reload_current_scene() functions in Godot

示例

输出

queue_free() and reload_current_scene() functions in Godot
queue_free() and reload_current_scene() functions in Godot
queue_free() and reload_current_scene() functions in Godot
queue_free() and reload_current_scene() functions in Godot

在这里,我们将 Label 名称从 Ok 更改为 again!

queue_free() and reload_current_scene() functions in Godot

如果我们再次按下按钮,我们可以从这里继续创建一个新故事。

在下一个教程中,我们将学习 Dictionaries。