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.
Checking the stable version of the documentation...
PackedScene
继承: Resource < RefCounted < Object
对序列化场景的抽象。
描述
场景文件的简化接口。提供可以对场景资源本身进行的操作和检查。
可以用来将某个节点保存到文件中。保存时,会将该节点和它所拥有的所有节点一起保存(见 Node.owner 属性)。
注意:该节点不必自我拥有。
示例:加载已保存的场景:
# 如果路径在编译期不可知,请使用 load() 而不是 preload()。
var scene = preload("res://scene.tscn").instantiate()
# 将该节点添加为脚本附加节点的子节点。
add_child(scene)
// C# 没有 preload,所以你使用的永远是 ResourceLoader.Load<PackedScene>()。
var scene = ResourceLoader.Load<PackedScene>("res://scene.tscn").Instantiate();
// 将该节点添加为脚本附加节点的子节点。
AddChild(scene);
示例:保存不同所有者的节点。下面的例子会创建 3 个对象:Node2D(node
)、RigidBody2D(body
)、CollisionObject2D(collision
))。node
的下一级是 body
,再下一级是 collision
。只有 body
被 node
拥有,因此 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("将场景保存到磁盘时出错。")
// 创建对象。
var node = new Node2D();
var body = new RigidBody2D();
var collision = new CollisionShape2D();
// 创建对象架构。
body.AddChild(collision);
node.AddChild(body);
// 修改 `body` 的拥有者,但不修改 `collision` 的拥有者。
body.Owner = node;
var scene = new PackedScene();
// 只会打包 `node` 和 `body`。
Error result = scene.Pack(node);
if (result == Error.Ok)
{
Error error = ResourceSaver.Save(scene, "res://path/name.tscn"); // Or "user://..."
if (error != Error.Ok)
{
GD.PushError("将场景保存到磁盘时出错。");
}
}
教程
方法
can_instantiate() const |
|
get_state() const |
|
instantiate(edit_state: GenEditState = 0) const |
|
枚举
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 类似,但适用于场景作为另一个场景的基类实例化的情况。
注意:仅在编辑器构建中可用。
方法说明
bool can_instantiate() const 🔗
如果场景文件有节点,返回 true
。
SceneState get_state() const 🔗
返回代表场景文件内容的 SceneState。
Node instantiate(edit_state: GenEditState = 0) const 🔗
实例化该场景的节点架构。触发子场景的实例化。在根节点上触发 Node.NOTIFICATION_SCENE_INSTANTIATED 通知。
将 path
节点及其所有子节点打包到该 PackedScene 中。所有现有数据都将被清除。请参阅 Node.owner。