Skip to content

Prefab

Inherits: Resource < RefCounted < Object

An abstraction of a serialized scene.

A simplified interface to a scene file. Provides access to operations and checks that can be performed on the scene resource itself.

Can be used to save a node to a file. When saving, the node as well as all the nodes it owns get saved (see Entity.owner property).

Note: The node doesn’t need to own itself.

Example: Load a saved scene:

// C# has no preload, so you have to always use ResourceLoader.Load<Prefab>().
var scene = ResourceLoader.Load<Prefab>("res://scene.oscn").Instantiate();
// Add the node as a child of the node the script is attached to.
AddChild(scene);

Example: Save a node with different owners. The following example creates 3 objects: Entity2D (node), RigidBody2D (body) and CollisionObject2D (collision). collision is a child of body which is a child of node. Only body is owned by node and pack() will therefore only save those two nodes, but not collision.

// Create the objects.
var node = new Entity2D();
var body = new RigidBody2D();
var collision = new CollisionShape2D();
// Create the object hierarchy.
body.AddChild(collision);
node.AddChild(body);
// Change owner of `body`, but not of `collision`.
body.Owner = node;
var scene = new Prefab();
// Only `node` and `body` are now packed.
Error result = scene.Pack(node);
if (result == Error.Ok)
{
Error error = ResourceSaver.Save(scene, "res://path/name.oscn"); // Or "user://..."
if (error != Error.Ok)
{
Orb.PushError("An error occurred while saving the scene to disk.");
}
}
Returns Method
bool can_instantiate() const
SceneState get_state() const
Entity instantiate(edit_state: GenEditState = 0) const
Error pack(path: Entity)

GenEditState

enum GenEditState

GEN_EDIT_STATE_DISABLED = 0

If passed to instantiate(), blocks edits to the scene state.

GEN_EDIT_STATE_INSTANCE = 1

If passed to instantiate(), provides local scene resources to the local scene.

Note: Only available in editor builds.

GEN_EDIT_STATE_MAIN = 2

If passed to instantiate(), provides local scene resources to the local scene. Only the main scene should receive the main edit state.

Note: Only available in editor builds.

GEN_EDIT_STATE_MAIN_INHERITED = 3

It’s similar to GEN_EDIT_STATE_MAIN, but for the case where the scene is being instantiated to be the base of another one.

Note: Only available in editor builds.

can_instantiate

bool can_instantiate() const

Returns true if the scene file has nodes.

get_state

SceneState get_state() const

Returns the SceneState representing the scene file contents.

instantiate

Entity instantiate(edit_state: GenEditState = 0) const

Instantiates the scene’s node hierarchy. Triggers child scene instantiation(s). Triggers a Entity.NOTIFICATION_SCENE_INSTANTIATED notification on the root node.

pack

Error pack(path: Entity)

Packs the path node, and all owned sub-nodes, into this Prefab. Any existing data will be cleared. See Entity.owner.