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?