Up to date

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

PackedScene

继承: Resource < RefCounted < Object

对序列化场景的抽象。

描述

场景文件的简化接口。提供可以对场景资源本身进行的操作和检查。

可以用来将某个节点保存到文件中。保存时,会将该节点和它所拥有的所有节点一起保存(见 Node.owner 属性)。

注意:该节点不必自我拥有。

加载保存场景的示例:

# 如果路径在编译期不可知,请使用 load() 而不是 preload()。
var scene = preload("res://scene.tscn").instantiate()
# 将该节点添加为脚本附加节点的子节点。
add_child(scene)

保存不同所有者的节点的示例:下面的粒子会创建 3 个对象:Node2Dnode)、RigidBody2Dbody)、CollisionObject2Dcollision))。node 的下一级是 body,再下一级是 collision。只有 bodynode 拥有,因此 pack 只会保存两个节点,不会保存 collision

# 创建对象。
var node = Node2D.new()
var body = RigidBody2D.new()
var collision = CollisionShape2D.new()

# 创建对象架构。
body.add_child(collision)
node.add_child(body)

# 修改 `body` 的拥有者,但不修改 `collision` 的拥有者。
body.owner = node
var scene = PackedScene.new()

# 只会打包 `node` 和 `body`。
var result = scene.pack(node)
if result == OK:
    var error = ResourceSaver.save(scene, "res://path/name.tscn")  # Or "user://..."
    if error != OK:
        push_error("将场景保存到磁盘时出错。")

教程

属性

Dictionary

_bundled

{ "conn_count": 0, "conns": PackedInt32Array(), "editable_instances": [], "names": PackedStringArray(), "node_count": 0, "node_paths": [], "nodes": PackedInt32Array(), "variants": [], "version": 3 }

方法

bool

can_instantiate ( ) const

SceneState

get_state ( ) const

Node

instantiate ( GenEditState edit_state=0 ) const

Error

pack ( Node path )


枚举

enum GenEditState:

GenEditState GEN_EDIT_STATE_DISABLED = 0

如果传递给 instantiate,则会阻止对场景状态的编辑。

GenEditState GEN_EDIT_STATE_INSTANCE = 1

如果传递给 instantiate,则会向本地场景提供本地场景资源。

注意:仅在编辑器构建中可用。

GenEditState GEN_EDIT_STATE_MAIN = 2

如果传递给 instantiate,则会向本地场景提供本地场景资源。只有主场景应该接收主编辑状态。

注意:仅在编辑器构建中可用。

GenEditState GEN_EDIT_STATE_MAIN_INHERITED = 3

GEN_EDIT_STATE_MAIN 类似,但适用于场景作为另一个场景的基类实例化的情况。

注意:仅在编辑器构建中可用。


属性说明

Dictionary _bundled = { "conn_count": 0, "conns": PackedInt32Array(), "editable_instances": [], "names": PackedStringArray(), "node_count": 0, "node_paths": [], "nodes": PackedInt32Array(), "variants": [], "version": 3 }

场景内容的字典表示。

可用的字段包括资源的“rnames”和“variants”,节点的“node_count”、“nodes”、“node_paths”,基本场景子级覆盖的“editable_instances”,信号连接的“conn_count”和“conns”,以及 PackedScene 格式样式的版本“version”。


方法说明

bool can_instantiate ( ) const

如果场景文件有节点,返回 true


SceneState get_state ( ) const

返回代表场景文件内容的 SceneState


Node instantiate ( GenEditState edit_state=0 ) const

实例化该场景的节点架构。触发子场景的实例化。在根节点上触发 Node.NOTIFICATION_SCENE_INSTANTIATED 通知。


Error pack ( Node path )

包将忽略不属于给定节点的任何子节点。请参阅 Node.owner