In this answer I present a few approaches to run code in the editor. The first one is pretty much what you are already doing. If that is an option for you, it is an option for you.
The second is using
EditorScript. Which technically accomplishes the “without attaching it to a node in the scene tree” requirement. But it is limited in what it can do.
The third is using
EditorPlugin. Which solves the “run a tool script on project load” requirement. Except, oh, surprise, the Godot IDE has a scene tree, which is not the scene tree of the game. I believe that
EditorPlugin is what you want.
Well, I suppose there is another way: Writing a Godot Module (with C++), which require building Godot from source to include. See Compiling.
As you are aware, you can run GDScript in the IDE by making script a
tool script (using the
tool keyword). And you can check
Engine.editor_hint to know when the code is running in the IDE.
Following that idea, you can have
tool script, where check
true and then instance there whatever you want to run only on the editor. If what you instanced there, is only instanced there… Well, you can forgo further checking.
And yes, I suppose you can have it remove itself.
Create a new script that inherits from
EditorScript. Make sure it is a
tool script. Give it a
tool extends EditorScript func _run(): print("Hello from the Godot Editor!")
This script runs from the Script Editor. With the script open, go to the File menu, and select Run. You can also use secondary click on the script on the Scripts Panel (on the left of the Script Editor) and select Run in the contextual menu.
Go to the Project menu, then Project Settings, on the Plugin tab, click create.
It will open a dialog asking about the details of your plugin. At minimum give it a Name (first field), a subfolder (second field) and a Script Name (last field). You can leave the rest blank (and even edit it later).
It will generate a script that looks like this:
tool extends EditorPlugin func _enter_tree() -> void: pass func _exit_tree() -> void: pass
This script runs on the editor only. You can enable it and disable it on the Plugin tab of the Project Settings (where you create it). And yes, this is how you make plugins/addons for Godot.
When you enable it (or when you load a project where it is enabled) it will run
_enter_tree. Similarly when disabling (or unloading a project where it is enabled) it will run
To be clear, these will not run when you run the game (because, again, this script runs on the editor only).
Reminder: The Godot UI is made with Godot. It has a scene tree.
EditorPlugin API will give you access to more parts of the IDE that you usually would.
Refer to Editor plugins and
plugin folder of the official godot-demo-projects repository (on Github).