Is it possible to instantiate a node in the editor scene tree through code?
I have a @tool script (to run the code in the editor) and on _init I would like to create a new node of type CollisionShape2D and then add it as a child of the node who has the @tool script.
I tried the following:
func _init() -> void:
var coll = CollisionShape2D.new()
add_child(coll)
the code is being called from the editor, but I don’t see the CollisionShape2D added in the scene tree and to the node as a child.
There’s something weird though: the parent node (who has the @tool script) is an Area2D, who usually gives an alert if a shape is missing. The code above makes the warning go away, but I don’t see the CollisionShape2D added to the scene tree.
Am I missing something or isn’t possible to achieve what I’m trying to do in Godot?
I know that it works running the scene, but here I’m talking about instantiating a node in the scene tree without running the scene, so entirely from the editor, using code.
It doesn’t work either. Anyway I would like to add the node automatically, without the need to check a boolean.
It looks like a problem with the editor not updating the nodes in the scene tree, could it be?
The node was created first, and then the tool script was attached. This could be why it’s not working, in my opinion.
However, I don’t see a situation where you would need to do something every time you boot up the editor. My understanding is that you’re using a tool script to perform many annoying jobs all at once. If you need to do those tasks again, you can manually trigger the script to do them.
When you’re adding nodes via add_child in a tool script, the added node isn’t visible in the scene tree dock unless you set its owner. Here’s info in the docs.