TExcelTAD
Home › Godot 4 with GDScript › Instancing Scenes

Instancing Scenes

A scene saved to disk is a PackedScene resource: a recipe for a node tree. Instancing turns that recipe into real nodes. You do it in the editor when you drop a coin into a level, and in code when an enemy fires a bullet or a spawner creates a wave. One coin scene, a hundred coin instances; change the scene and every instance changes.

Instancing in the editor

  1. Build the coin as its own scene (res://coin/coin.tscn): an Area2D root with a Sprite2D and a CollisionShape2D.
  2. Open the level scene. Drag coin.tscn from the FileSystem dock into the 2D viewport, or select a parent node and click the Instantiate Child Scene button (the chain-link icon) in the Scene dock.
  3. The instance shows up as one node with a clapperboard icon. Its children are hidden because they belong to the coin scene; you edit them by opening coin.tscn (click the icon).
  4. You can still override the instance's own properties (position, exported variables) in the Inspector. Overridden properties get a revert arrow.

In the level's .tscn, an instance is just a reference plus the overrides:

ini
[ext_resource type="PackedScene" path="res://coin/coin.tscn" id="3_coin"]

[node name="Coins" type="Node2D" parent="."]

[node name="Coin" parent="Coins" instance=ExtResource("3_coin")]
position = Vector2(64, 32)

[node name="Coin2" parent="Coins" instance=ExtResource("3_coin")]
position = Vector2(96, 32)

Instancing in code

In a project, you load the scene and call instantiate():

gdscript
const CoinScene: PackedScene = preload("res://coin/coin.tscn")   # loaded when the script loads

func spawn_coin(at: Vector2) -> void:
	var coin := CoinScene.instantiate() as Area2D
	coin.position = at          # set properties before add_child, so _ready sees them
	add_child(coin)
  • preload("res://...") loads at compile time; the path must be a constant string. Use it for scenes you always need.
  • load(path) loads at runtime, from any string. Use it for levels chosen by name (load("res://levels/level_%02d.tscn" % n)).
  • Both return the same cached resource: loading a scene twice doesn't read the file twice.

The course runner has no .tscn files, but a PackedScene can also be made from nodes in code with pack(). That is what the editor does when you save. The example below packs a coin and instances it three times:

gdscript · try it yourself
extends Node2D

# frames: 0
var coin_scene: PackedScene

func build_coin_scene() -> PackedScene:
	# In a project this is coin.tscn, made in the editor.
	var coin := Area2D.new()
	coin.name = "Coin"
	var sprite := Sprite2D.new()
	sprite.name = "Sprite"
	coin.add_child(sprite)
	sprite.owner = coin          # only nodes owned by the root are saved
	var shape := CollisionShape2D.new()
	shape.name = "Shape"
	var circle := CircleShape2D.new()
	circle.radius = 6.0
	shape.shape = circle
	coin.add_child(shape)
	shape.owner = coin
	var scene := PackedScene.new()
	scene.pack(coin)
	coin.free()                  # the template node is no longer needed
	return scene

func _ready():
	coin_scene = build_coin_scene()
	for i in 3:
		var coin := coin_scene.instantiate() as Area2D
		coin.position = Vector2(32 * i, 0)
		add_child(coin)
	for c in get_children():
		print(c.name, " at ", c.position, ", children: ", c.get_child_count())
Coin at (0.0, 0.0), children: 2
@Area2D@2 at (32.0, 0.0), children: 2
@Area2D@3 at (64.0, 0.0), children: 2

Two lessons hide in that output:

  • owner matters. A node added in code is saved into a scene (or a pack()) only if its owner is the scene root. The editor sets it for you; code that builds a tree to save must set it.
  • Sibling names must be unique. All three instances are called Coin, so Godot renames the second and third to @Area2D@2 and @Area2D@3. Those names are not stable, so never look up spawned nodes by such names. Keep a reference, use a group, or set a name yourself.
gdscript · try it yourself
extends Node2D

# frames: 0

func _ready():
	var scene := PackedScene.new()
	var template := Node2D.new()
	template.name = "Enemy"
	scene.pack(template)
	template.free()

	var a := scene.instantiate()
	add_child(a)
	var b := scene.instantiate()
	add_child(b, true)               # force_readable_name: "Enemy2" instead of "@Node2D@2"
	var c := scene.instantiate()
	c.name = "Boss"                  # or choose the name before adding it
	add_child(c)
	for n in get_children():
		print(n.name)
Enemy
Enemy2
Boss

The shared-resource trap

Instances share the resources of their scene: textures, materials, shapes. That saves memory, but changing a shared resource from one instance changes it for all of them:

gdscript · try it yourself
extends Node

# frames: 0

func make_scene(local: bool) -> PackedScene:
	var root := Area2D.new()
	var shape := CollisionShape2D.new()
	shape.name = "Shape"
	var circle := CircleShape2D.new()
	circle.radius = 6.0
	circle.resource_local_to_scene = local
	shape.shape = circle
	root.add_child(shape)
	shape.owner = root
	var scene := PackedScene.new()
	scene.pack(root)
	root.free()
	return scene

func _ready():
	for local in [false, true]:
		var scene := make_scene(local)
		var a := scene.instantiate()
		var b := scene.instantiate()
		a.get_node("Shape").shape.radius = 20.0    # a power-up grows one coin
		print("local_to_scene=", local, ": b's radius is ", b.get_node("Shape").shape.radius)
		a.free()
		b.free()
local_to_scene=false: b's radius is 20.0
local_to_scene=true: b's radius is 6.0

Two fixes:

  • tick Local to Scene on the resource in the Inspector (resource_local_to_scene = true), so every instance gets its own copy; or
  • duplicate it in code before changing it: shape.shape = shape.shape.duplicate().

Resources & .tres Files covers this in depth, including your own resource types.

Inherited scenes vs composition

Scene > New Inherited Scene creates a scene that extends another one (an "elite enemy" based on "enemy"): it keeps the base's nodes and can override them. It is handy for variants that differ only in properties. For behaviour, prefer composition: small scenes such as Health, Hitbox or Wanderer instanced as children. Deep inheritance chains break when the base scene changes; see Field Notes: Scene Architecture.

Test yourself

What is the difference between preload() and load()?

  1. preload is for scripts only
  2. preload takes a constant path and loads when the script is loaded; load takes any path at runtime
  3. load returns a copy, preload a shared resource
  4. There is none

Three coins named Coin are added to the same parent. What are the names of the second and third?

  1. Coin, Coin
  2. Coin2, Coin3, always
  3. Generated names like @Area2D@2, unless you pass force_readable_name or set a name first
  4. Godot raises an error

Changing $Shape.shape.radius on one coin instance changes every coin. Why?

  1. A bug in Godot
  2. Instances share the scene's resources; mark it Local to Scene or duplicate() it
  3. The coins are in the same group
  4. radius is a static variable