I wonder when to use PackedScene.instantiate() vs. MyNode.new().

I have set up this example comparing the two, where I have a custom label node that is being created both one way and the other and added to a main scene.

# FILE 1: my_label.tscn
# This is a custom label
class_name MyLabel
extends Label

func _init(a: String = "Default") -> void:
	self.text = a


# FILE 2: main.tscn
# This is the main scene, where to custom labels will be added.
extends VBoxContainer

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	# Create instance via PackedScene.
	var instanciated_label: MyLabel = preload("res://my_label.tscn").instantiate()
	add_child(instanciated_label)	
	# Create instance via Node.new().
	var new_label := MyLabel.new("Hello")
	add_child(new_label)

What are the pros and cons for each method?
One difference is the way _init() is called: Using the second way, I can pass a value to _init(), so the label will display the word "Hello", whereas the first label will display "Default". Is this possible using the first way?
Is the first way faster, after the preload is done?

  • xyz replied to this.

    Dodo_87 new() can only create one node whereas instantiate() is meant to create whole hierarchies.

      xyz Thank you! I have just adapted my example and am quite surprised that children of MyLabel are not instantiated. That's what you said, but still I do not understand why one would actually want this and it even seems inconsistent.

      Assume:

      	var spin_box = SpinBox.new()
      	add_child(spin_box)

      This gives me a complete SpinBox, even though the SpinBox itself seems to be a hierarchy. (I have not checked the code, it obviously is composed of several elements.

      So the internal structure of the SpinBox does not matter, when I create it with new(). In contrast, it does matter if I create MyLabelwith new().

      Do you know the reason to this?

      • xyz replied to this.

        Dodo_87 SpinBox is a single node while your label is a scene likely composed of multiple nodes. Furthermore SpinBox is a class while your scene isn't a class. It just has a script of your custom class attached to its top node.

          xyz That does make sense! Thank you for your explanation!