CodeBlanks Logo Icon CodeBlanks

Scene instance

Learn to instance a saved scene as a child node.

Instancing with instantiate()

Creating a new copy from a saved PackedScene resource is called scene instancing. In GDScript, this is done using the instantiate() method. For example, dozens of copies of a bullet or enemy resource can be spawned this way.

var sahne: PackedScene = preload("res://Dusman.tscn")
var yeni_dusman = sahne.instantiate()

Adding to Tree with add_child()

An object created with instantiate() initially exists only in memory; it must be added to the scene tree to appear on screen. To place a node under another node, the add_child(yeni_dugum) function is used.

var yeni_obje = sahne.instantiate()
add_child(yeni_obje)
print("Düğüm ağaca eklendi")

Practice Create and Add Node

Inside _ready(), create a new node with Node2D.new(), add it with add_child(), and print print("Örnek eklendi") to the screen.

Starter code

Player.cs
extends Node

func _ready():
    # Yeni Node2D oluştur, add_child ile ekle ve mesaj yazdır
    pass

Sample solution

Player.cs
extends Node

func _ready():
    var nesne = Node2D.new()
    add_child(nesne)
    print("Örnek eklendi")

Expected output

Örnek eklendi

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method is called to create a new node copy from a PackedScene resource?

  • instantiate() Correct answer
  • duplicate_tree()
  • create_scene()
  • spawn_node()

Explanation: The instantiate() method is used to produce a new node hierarchy from PackedScene objects.

2 Add new node as child

Question
var yeni_obje = sahne.instantiate()
____(yeni_obje)
Answer
var yeni_obje = sahne.instantiate()
add_child(yeni_obje)

Explanation: add_child() is used to attach a child node to the scene tree.

3 Instancing Terms

Term Meaning
instantiate() Creates a node from a PackedScene
add_child() Adds node as a child in scene tree
preload() Loads a scene or resource in advance
get_parent() Returns the attached parent node

All lessons in Beginner