How can I add children to a child Node of the current Scene in the Editor programmatically?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By rafgp

I created a class_name node called State. I want to programmatically add new State nodes to the current scene being edited in the editor (e.g. Player scene), which has a child node called “States”. The tree looks like this:

Player:
|_ Sprite
|_ CollisionShape2D
|_ …
|_ States (of type Node)
\ \ |_ (Here is where I want to insert new “State” nodes)

OK. So I made this EditorScript script:

tool
extends EditorScript

var states = [
	"Idle",
	"Walking",
	"Jumping",
	"Falling"
]

func  _run() -> void:
	var root = get_scene()
	var states_node = root.get_node("States")
	remove_undesired(root, states)
	remove_undesired(states_node, states)
	add_state_node(states_node, states)
	get_scene().print_tree_pretty()

func remove_undesired(node, names):
	for target in node.get_children():
		for name in names:
			if (target.name as String).to_lower().begins_with(name.to_lower()):
				(target as Node).get_parent().remove_child(target)
				(target as Node).queue_free()

func add_state_node(states_node, states):
	for state in states:
		var new_state = State.new()
		new_state.name = state
		states_node.add_child(new_state)
		new_state.set_owner(states_node)

Every time I run this script, it apparently adds the children to the tree in the right spot, but they do NOT appear on the editor tree visualization. The output in the console is the following (due to the print_tree_pretty() call:

But it does not add to the editor visualization:

:bust_in_silhouette: Reply From: Dlean Jeans

The owner of your states should be the Player scene. Thus the last line:

new_state.set_owner(get_scene())