Up to date
This page is up to date for Godot 4.1
.
If you still find outdated information, please open an issue.
Running code in the editor¶
What is @tool
?¶
@tool
is a powerful line of code that, when added at the top of your script,
makes it execute in the editor. You can also decide which parts of the script
execute in the editor, which in game, and which in both.
You can use it for doing many things, but it is mostly useful in level design for visually presenting things that are hard to predict ourselves. Here are some use cases:
If you have a cannon that shoots cannonballs affected by physics (gravity), you can draw the cannonball's trajectory in the editor, making level design a lot easier.
If you have jumppads with varying jump heights, you can draw the maximum jump height a player would reach if it jumped on one, also making level design easier.
If your player doesn't use a sprite, but draws itself using code, you can make that drawing code execute in the editor to see your player.
Danger
@tool
scripts run inside the editor, and let you access the scene tree
of the currently edited scene. This is a powerful feature which also comes
with caveats, as the editor does not include protections for potential
misuse of @tool
scripts.
Be extremely cautious when manipulating the scene tree, especially via
Node.queue_free, as it can cause
crashes if you free a node while the editor runs logic involving it.
How to use it¶
To turn a script into a tool, add the @tool
annotation at the top of your code.
To check if you are currently in the editor, use: Engine.is_editor_hint()
.
For example, if you want to execute some code only in the editor, use:
if Engine.is_editor_hint():
# Code to execute when in editor.
if (Engine.IsEditorHint())
{
// Code to execute when in editor.
}
On the other hand, if you want to execute code only in game, simply negate the same statement:
if not Engine.is_editor_hint():
# Code to execute when in game.
if (!Engine.IsEditorHint())
{
// Code to execute when in game.
}
Pieces of code that do not have either of the 2 conditions above will run both in-editor and in-game.
Here is how a _process()
function might look for you: