Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
Ejecutando código en el 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.
Puedes usarlo para hacer muchas cosas, pero es especialmente útil en el diseño de niveles para presentar visualmente cosas que son difíciles de predecir por nosotros mismos. Aquí hay algunos casos de uso:
Si tienes un cañón que dispara balas de cañón afectadas por la física (gravedad), puedes dibujar la trayectoria de las balas de cañón en el editor, lo que facilitará mucho el diseño de niveles.
Si tienes plataformas de salto (jumppads) con alturas de salto variables, puedes dibujar la altura máxima a la que llegaría un jugador si saltara sobre una, lo que también facilitaría el diseño de niveles.
Si tu jugador no utiliza un sprite, sino que se dibuja a sí mismo usando código, puedes hacer que ese código de dibujo se ejecute en el editor para ver a tu jugador.
Peligro
@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.
Cómo usarlo¶
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()
.
Por ejemplo, si desea ejecutar algún código solo en el editor, use:
if Engine.is_editor_hint():
# Code to execute when in editor.
if (Engine.IsEditorHint())
{
// Code to execute when in editor.
}
Por otro lado, si desea ejecutar código solo en el juego, simplemente niegue la misma declaración:
if not Engine.is_editor_hint():
# Code to execute when in game.
if (!Engine.IsEditorHint())
{
// Code to execute when in game.
}
Los fragmentos de código que no tienen ninguna de las 2 condiciones mencionadas anteriormente se ejecutarán tanto en el editor como en el juego.
Aquí tienes cómo podría lucir una función _process()
para ti:
func _process(delta):
if Engine.is_editor_hint():
# Code to execute in editor.
if not Engine.is_editor_hint():
# Code to execute in game.
# Code to execute both in editor and in game.
public override void _Process(double delta)
{
if (Engine.IsEditorHint())
{
// Code to execute in editor.
}
if (!Engine.IsEditorHint())
{
// Code to execute in game.
}
// Code to execute both in editor and in game.
}
Nota
Modifications in the editor are permanent. For example, in the following case, when we remove the script, the node will keep its rotation. Be careful to avoid making unwanted modifications.
Pruebalo¶
Add a Sprite2D
node to your scene and set the texture to Godot icon. Attach
and open a script, and change it to this:
@tool
extends Sprite2D
func _process(delta):
rotation += PI * delta
using Godot;
[Tool]
public partial class MySprite : Sprite2D
{
public override void _Process(double delta)
{
Rotation += Mathf.Pi * (float)delta;
}
}
Guarda el script y regresa al editor. Ahora deberías ver que tu objeto rota. Si ejecutas el juego, también rotará.

Nota
Si no ves los cambios, recarga la escena (ciérrala y ábrela nuevamente).
Ahora elijamos qué código se ejecutará cuándo. Modifica tu función _process()
para que se vea así:
func _process(delta):
if Engine.is_editor_hint():
rotation += PI * delta
else:
rotation -= PI * delta
public override void _Process(double delta)
{
if (Engine.IsEditorHint())
{
Rotation += Mathf.Pi * (float)delta;
}
else
{
Rotation -= Mathf.Pi * (float)delta;
}
}
Guarda el script. Ahora el objeto girará en sentido horario en el editor, pero si ejecutas el juego, girará en sentido antihorario.
Editando variables¶
Add and export a variable speed to the script. To update the speed and also reset the rotation
angle add a setter set(new_speed)
which is executed with the input from the inspector. Modify
_process()
to include the rotation speed.
@tool
extends Sprite2D
@export var speed = 1:
# Update speed and reset the rotation.
set(new_speed):
speed = new_speed
rotation = 0
func _process(delta):
rotation += PI * delta * speed
using Godot;
[Tool]
public partial class MySprite : Sprite2D
{
private float _speed = 1;
[Export]
public float Speed
{
get => _speed;
set
{
// Update speed and reset the rotation.
_speed = value;
Rotation = 0;
}
}
public override void _Process(double delta)
{
Rotation += Mathf.Pi * (float)delta * speed;
}
}
Nota
Code from other nodes doesn't run in the editor. Your access to other nodes is limited. You can access the tree and nodes, and their default properties, but you can't access user variables. If you want to do so, other nodes have to run in the editor too. Autoload nodes cannot be accessed in the editor at all.
Reporting node configuration warnings¶
Godot uses a node configuration warning system to warn users about incorrectly configured nodes. When a node isn't configured correctly, a yellow warning sign appears next to the node's name in the Scene dock. When you hover or click on the icon, a warning message pops up. You can use this feature in your scripts to help you and your team avoid mistakes when setting up scenes.
When using node configuration warnings, when any value that should affect or remove the warning changes, you need to call update_configuration_warnings . By default, the warning only updates when closing and reopening the scene.
# Use setters to update the configuration warning automatically.
@export var title = "":
set(p_title):
if p_title != title:
title = p_title
update_configuration_warnings()
@export var description = "":
set(p_description):
if p_description != description:
description = p_description
update_configuration_warnings()
func _get_configuration_warnings():
var warnings = []
if title == "":
warnings.append("Please set `title` to a non-empty value.")
if description.length() >= 100:
warnings.append("`description` should be less than 100 characters long.")
# Returning an empty array means "no warning".
return warnings
Instanciación de escenas¶
Puedes instanciar escenas empaquetadas normalmente y agregarlas a la escena que está abierta actualmente en el editor. Por defecto, los nodos o escenas añadidos con Node.add_child(node) no son visibles en el panel del árbol de escena (Scene tree dock) y no se guardan en el disco. Si deseas que el nodo o la escena sean visibles en el panel del árbol de escena y se guarden en el disco al guardar la escena, debes establecer la propiedad owner del nodo hijo en el nodo raíz de la escena que está siendo editada actualmente.
If you are using @tool
:
func _ready():
var node = Node3D.new()
add_child(node) # Parent could be any node in the scene
# The line below is required to make the node visible in the Scene tree dock
# and persist changes made by the tool script to the saved scene file.
node.set_owner(get_tree().edited_scene_root)
public override void _Ready()
{
var node = new Node3D();
AddChild(node); // Parent could be any node in the scene
// The line below is required to make the node visible in the Scene tree dock
// and persist changes made by the tool script to the saved scene file.
node.Owner = GetTree().EditedSceneRoot;
}
Si estás usando EditorScript:
func _run():
# `parent` could be any node in the scene.
var parent = get_scene().find_node("Parent")
var node = Node3D.new()
parent.add_child(node)
# The line below is required to make the node visible in the Scene tree dock
# and persist changes made by the tool script to the saved scene file.
node.set_owner(get_scene())
public override void _Run()
{
// `parent` could be any node in the scene.
var parent = GetScene().FindNode("Parent");
var node = new Node3D();
parent.AddChild(node);
// The line below is required to make the node visible in the Scene tree dock
// and persist changes made by the tool script to the saved scene file.
node.Owner = GetScene();
}
Advertencia
Using @tool
improperly can yield many errors. It is advised to first
write the code how you want it, and only then add the @tool
annotation to
the top. Also, make sure to separate code that runs in-editor from code that
runs in-game. This way, you can find bugs more easily.