Through code, I wish to instance a scene

In my main scene, game.tscsn, I'm using this code...

func _ready():
	
	# create an instance of trainWheel	
	# 1. Preload it - now, it's currently a packed scene
	var scene = preload("res://trainWheel.tscn")

	# step 2, turn the packed scene into a node
	var instance = scene.instance()
	
	# step 3, put our node into the tree where we need it
	add_child(instance)

Is this correct? Should this node now be visible in my scene inspector?

That code looks correct. The node is added at runtime, so if you want to see the node in the Inspector, you'll need to click the Remote tab in the Scene Dock, while the project is playing.

@DaveTheCoder said: That code looks correct. The node is added at runtime, so if you want to see the node in the Inspector, you'll need to click the Remote tab in the Scene Dock, while the project is playing.

thank you for the tip

Struggling to create the instance and make it a child of the current node's parent?

var parent = self.get_parent()
parent.add_child(instance)

Yes, as long as the node to which the child is parented is in the scene tree when the code is executed, and the correct node path to the parent is specified.

this seems to solve the parent.add_child(instance) issue

get_parent().call_deferred("add_child", instance)

can anyone explain why?

You're adding the node in _ready(). A node is added to the scene tree after its children, so the node's parent is not yet in the scene tree.

If B is a child of A, and C is a child of B, then the ready() methods are called in the order C B A. You can verify that by putting print statements in the ready() methods.

Try putting the code add_child(whatever) directly onto the parent

@Nerdzmasterz said: Try putting the code add_child(whatever) directly onto the parent

Would it be prudent to emit a signal from the child node, to say the scene's root node, and do the add_child from there?

6 months later