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.

Criando plugins de tela principal

O que este tutorial aborda

Plugins de tela principal permitem criar novas IUs na parte central do editor, que aparecem ao lado dos botões '2D', '3D', 'Script', 'Game' e 'AssetLib'. Tais plugins de editor são chamados de 'plugins de tela principal' (Main screen plugins).

Este tutorial orienta você na criação de um plugin básico de tela principal. Para fins de simplicidade, nosso plugin de tela principal conterá um único botão que exibe um texto no console.

Inicializando o plugin

Primeiro, crie um novo plugin a partir do menu Plugins. Para este tutorial, nós o colocaremos em uma pasta chamada main_screen, mas você pode usar o nome que preferir.

O script do plugin virá com os métodos _enter_tree() e _exit_tree(), mas para um plugin de tela principal, precisamos adicionar alguns métodos extras. Adicione quatro métodos extras para que o script fique assim:

@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.

Cena da tela principal

Crie uma nova cena com um nó raiz derivado de Control (para este plugin de exemplo, faremos do nó raiz um CenterContainer). Selecione este nó raiz e, na viewport, clique no menu Layout e selecione Full Rect. Você também precisa habilitar a flag de tamanho vertical Expand no inspetor. O painel agora usa todo o espaço disponível na viewport principal.

A seguir, vamos adicionar um botão ao nosso plugin de exemplo de tela principal. Adicione um nó Button e defina o texto como "Print Hello" ou semelhante. Adicione um script ao botão assim:

@tool
extends Button


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

Em seguida, conecte o sinal "pressed" a si mesmo. Se precisar de ajuda com sinais, consulte o artigo Usando sinais.

Terminamos o painel da tela principal. Salve a cena como main_panel.tscn.

Atualizar o script do plugin

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.

A função _exit_tree() é chamada quando o plugin é desativado. Se a tela principal ainda existir, chamamos queue_free() para liberar a instância e removê-la da memória.

A função _make_visible() é sobrescrita para ocultar ou mostrar o painel principal conforme necessário. Essa função é chamada automaticamente pelo editor quando o usuário clica nos botões da janela de visualização principal no topo do editor.

As funções _get_plugin_name() e _get_plugin_icon() controlam o nome e o ícone exibidos para o botão da janela de visualização principal do plugin.

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 Ícones do editor for information on how to create icons for your plugin.

Testando o plugin

Ative o plugin nas Configurações do Projeto. Você observará um novo botão ao lado de 2D, 3D e Script acima da janela de visualização principal. Clicar nele levará você ao seu novo plugin de tela principal, e o botão no meio exibirá o texto.

Se você quiser testar uma versão finalizada deste plugin, confira as demonstrações de plugins aqui: https://github.com/godotengine/godot-demo-projects/tree/master/plugins

Se você quiser ver um exemplo mais completo do que os plugins de tela principal são capazes de fazer, confira os projetos de demonstração 2.5D aqui: https://github.com/godotengine/godot-demo-projects/tree/master/misc/2.5d