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。