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.

Создание плагинов главного экрана

Что охватывает этот урок

Плагины главного экрана позволяют создавать новые пользовательские интерфейсы в центральной части редактора, которые отображаются рядом с кнопками "2D", "3D", "Script", "Game", и "AssetLib". Такие плагины редактора называются "Main screen plugins".

В этом руководстве мы покажем вам, как создать простой плагин для главного экрана. Для простоты наш плагин будет содержать одну кнопку, которая выводит текст в консоль.

Инициализация плагина

Сначала создайте новый плагин в меню Plugins. В этом руководстве мы поместим его в папку main_screen, но вы можете использовать любое другое имя.

Скрипт плагина будет содержать методы _enter_tree() и _exit_tree(), но для плагина главного экрана нам нужно добавить несколько дополнительных методов. Добавьте четыре дополнительных метода, чтобы скрипт выглядел так:

@tool
extends EditorPlugin


func _enter_tree():
    pass


func _exit_tree():
    pass


func _has_main_screen():
    return true


func _make_visible(visible):
    pass


func _get_plugin_name():
    return "Main Screen Plugin"


func _get_plugin_icon():
    return EditorInterface.get_editor_theme().get_icon("Node", "EditorIcons")

The important part in this script is the _has_main_screen() function, which is overridden to return true. This function is automatically called by the editor on plugin activation, to tell it that this plugin adds a new center view to the editor. For now, we'll leave this script as-is and we'll come back to it later.

Главная сцена экрана

Создайте новую сцену с корневым узлом, производным от Control (в этом примере плагина мы сделаем корневым узлом CenterContainer). Выберите этот корневой узел и в области просмотра нажмите меню Layout и выберите Full Rect. Также необходимо включить флажок Expand для вертикального размера в инспекторе. Теперь панель занимает всё доступное пространство в основной области просмотра.

Теперь добавим кнопку в наш пример плагина главного экрана. Добавьте узел Button и задайте текст "Print Hello" или аналогичный. Добавьте скрипт к кнопке следующим образом:

@tool
extends Button


func _on_print_hello_pressed():
    print("Hello from the main screen plugin!")

Затем соедините сигнал "pressed" с самим собой. Если вам нужна помощь с сигналами, см. статью Использование сигналов.

С панелью главного экрана всё готово. Сохраните сцену как main_panel.tscn.

Обновите скрипт плагина

We need to update the main_screen_plugin.gd script so the plugin instantiates our main panel scene and places it where it needs to be. Here is the full plugin script:

@tool
extends EditorPlugin


const MainPanel = preload("res://addons/main_screen/main_panel.tscn")

var main_panel_instance


func _enter_tree():
    main_panel_instance = MainPanel.instantiate()
    # Add the main panel to the editor's main viewport.
    EditorInterface.get_editor_main_screen().add_child(main_panel_instance)
    # Hide the main panel. Very much required.
    _make_visible(false)


func _exit_tree():
    if main_panel_instance:
        main_panel_instance.queue_free()


func _has_main_screen():
    return true


func _make_visible(visible):
    if main_panel_instance:
        main_panel_instance.visible = visible


func _get_plugin_name():
    return "Main Screen Plugin"


func _get_plugin_icon():
    # Must return some kind of Texture for the icon.
    return EditorInterface.get_editor_theme().get_icon("Node", "EditorIcons")

A couple of specific lines were added. MainPanel is a constant that holds a reference to the scene, and we instantiate it into main_panel_instance.

The _enter_tree() function is called before _ready(). This is where we instantiate the main panel scene, and add them as children of specific parts of the editor. We use EditorInterface.get_editor_main_screen() to obtain the main editor screen and add our main panel instance as a child to it. We call the _make_visible(false) function to hide the main panel so it doesn't compete for space when first activating the plugin.

Функция _exit_tree() вызывается при деактивации плагина. Если главный экран всё ещё существует, мы вызываем queue_free(), чтобы освободить экземпляр и удалить его из памяти.

Функция _make_visible() переопределяется для скрытия или отображения главной панели по мере необходимости. Эта функция автоматически вызывается редактором при нажатии пользователем на кнопки главной области просмотра в верхней части редактора.

Функции _get_plugin_name() и _get_plugin_icon() управляют отображаемым именем и значком для главной кнопки области просмотра плагина.

Another function you can add is the _handles() function, which allows you to handle a node type, automatically focusing the main screen when the type is selected. This is similar to how clicking on a 3D node will automatically switch to the 3D viewport.

Main screen icons

You can either use one of the built-in icons from the editor, or provide your own icon for the main screen plugin. In both cases, this is done by overriding the _get_plugin_icon() method in the plugin script.

To use a built-in icon, copy an icon name from the Godot editor icons website. Use the name copied from the website as the first parameter of EditorInterface.get_editor_theme().get_icon() (the second parameter should remain "EditorIcons").

You can use a custom icon by returning something such as preload("res://addons/main_screen/icon.svg"). When designing your own icon, you should follow the same guidelines as for node icons (SVG format recommended, 16×16 size). See Иконки редактора for information on how to create icons for your plugin.

Попробуйте плагин

Активируйте плагин в настройках проекта. Вы увидите новую кнопку рядом с пунктами 2D, 3D, Script над основным окном просмотра. Нажав на неё, вы перейдёте к новому плагину главного экрана, а кнопка посередине выведет текст.

Если вы хотите попробовать готовую версию этого плагина, ознакомьтесь с демонстрациями плагинов здесь: https://github.com/godotengine/godot-demo-projects/tree/master/plugins

Если вы хотите увидеть более полный пример того, на что способны плагины главного экрана, ознакомьтесь с демонстрационными проектами 2.5D здесь: https://github.com/godotengine/godot-demo-projects/tree/master/misc/2.5d