Запуск кода в редакторе¶
Что такое tool
?¶
tool
это мощная строка кода, которая будучи добавлена на верх вашего скрипта, делает его выполняемым в редакторе. Вы также можете определить какие части скрипта будут выполняться в редакторе, какие в игре, а какие и там и там.
Вы можете использовать её для достижения многих вещей, но это наиболее полезно для дизайна уровней и визуальных представлений вещей которые сложно предсказать. Здесь показаны некоторые примеры использования:
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.
Если у вас есть прыжковые платформы с различными высотами прыжка, для каждой из них вы сможете нарисовать максимальную высоту на которую игрок может подпрыгнуть, что также делает дизайн уровней лёгким.
Если ваш игрок не использует спрайт, но рисует его из кода, вы можете сделать эту отрисовку выполняемой в редакторе так что вы увидите вашего игрока.
Опасно
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.
Как использовать это¶
To turn a script into a tool, add the keyword tool
at the top of your code.
Для проверки что вы находитесь в редакторе, используйте Engine.editor_hint
.
For example, if you want to execute some code only in the editor, use:
if Engine.editor_hint:
# Code to execute when in editor.
if (Engine.EditorHint)
{
// 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.editor_hint:
# Code to execute when in game.
if (!Engine.EditorHint)
{
// Code to execute when in game.
}
Pieces of code 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:
func _process(delta):
if Engine.editor_hint:
# Code to execute in editor.
if not Engine.editor_hint:
# Code to execute in game.
# Code to execute both in editor and in game.
public override void _Process(float delta)
{
if (Engine.EditorHint)
{
// Code to execute in editor.
}
if (!Engine.EditorHint)
{
// Code to execute in game.
}
// Code to execute both in editor and in game.
}
Примечание
Modifications in 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.
Попробуйте¶
Добавьте нод Sprite
на вашу сцену и установить текстуру на иконку Godot. Присоедините и откройте скрипт, и измените его на это:
tool
extends Sprite
func _process(delta):
rotation_degrees += 180 * delta
using Godot;
using System;
[Tool]
public class MySprite : Sprite
{
public override void _Process(float delta)
{
RotationDegrees += 180 * delta;
}
}
Сохраните скрипт и вернитесь в редактор. Вы должны увидеть как ваш объект вращается. Если вы запустите игру, он также будет вращаться.

Примечание
Если вы не увидели изменений, перезагрузите сцену (закройте и откройте снова).
Теперь давайте выберем когда и какой код запустится. Измените функцию _process()
чтобы она выглядела вот так:
func _process(delta):
if Engine.editor_hint:
rotation_degrees += 180 * delta
else:
rotation_degrees -= 180 * delta
public override void _Process(float delta)
{
if (Engine.EditorHint)
{
RotationDegrees += 180 * delta;
}
else
{
RotationDegrees -= 180 * delta;
}
}
Сохраните скрипт. Теперь объект будет вращаться по часовой стрелке в редакторе, но если вы запустите игру он будет вращаться против часовой стрелки.
Editing variables¶
Добавьте и экспортируйте переменную speed в скрипт. Функция set_speed после "setget" выполняется с вашим вводом для изменения переменной. Модифицируйте _process()
, чтобы включить скорость вращения.
tool
extends Sprite
export var speed = 1 setget set_speed
# Update speed and reset the rotation.
func set_speed(new_speed):
speed = new_speed
rotation_degrees = 0
func _process(delta):
rotation_degrees += 180 * delta * speed
using Godot;
using System;
[Tool]
public class MySprite : Sprite
{
private float speed = 1;
[Export]
public float Speed {
get => speed;
set => SetSpeed(value);
}
// Update speed and reset the rotation.
private void SetSpeed(float newSpeed)
{
speed = newSpeed;
RotationDegrees = 0;
}
public override void _Process(float delta)
{
RotationDegrees += 180 * delta * speed;
}
}
Примечание
Код из других нодов не запускается в редакторе. Ваш доступ к другим нодам ограничен. Вы можете получить доступ к древу и нодам, и их свойствам по умолчанию, но вы не можете получить доступ к переменным пользователя. Если вы хотите сделать это, другие ноды должны также запустится в редакторе. AutoLoad ноды не могут быть доступны из редактора вообще.
Инстанцирование сцен¶
You can instantiate packed scenes normally and add them to the scene currently opened in the editor. By default, nodes or scenes added with Node.add_child(node) are not visible in the Scene tree dock and are not persisted to disk. If you wish the node or scene to be visible in the scene tree dock and persisted to disk when saving the scene, you need to set the child node's owner property to the currently edited scene root.
Если вы используете tool
:
func _ready():
var node = Spatial.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 Spatial();
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;
}
Если вы используете EditorScript:
func _run():
var parent = get_scene().find_node("Parent") # Parent could be any node in the scene
var node = Spatial.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()
{
var parent = GetScene().FindNode("Parent"); // Parent could be any node in the scene
var node = new Spatial();
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();
}
Предупреждение
Неправильное использование tool
может привести к многочисленным ошибкам. Рекомендуется сначала написать код так, как вы хотите, и только потом добавить ключевое слово tool
в начало. Кроме того, убедитесь, что код, который выполняется в редакторе, отделен от кода, который выполняется в игре. Так вам будет легче найти ошибки.