Work in progress

The content of this page was not yet updated for Godot 4.2 and may be outdated. If you know how to improve this page or you can confirm that it's up to date, feel free to open a pull request.

Creando plugins para pantalla principal

Qué cubre este tutorial

Main screen plugins allow you to create new UIs in the central part of the editor, which appear next to the "2D", "3D", "Script", and "AssetLib" buttons. Such editor plugins are referred as "Main screen plugins".

Este tutorial le guía a través de la creación de un plugin de pantalla principal básico. En aras de la simplicidad, nuestro plugin de pantalla principal contendrá un solo botón que imprime texto en la consola.

Inicializando el plugin

Primero crea un nuevo plugin desde el menú Plugins. Para este tutorial, lo pondremos en una carpeta llamada ''main_screen'', pero puedes usar cualquier nombre que quieras.

El script del plugin vendrá con los métodos ''_enter_tree()'' y ''_exit_tree()'', pero para un plugin de pantalla principal necesitamos agregar algunos métodos adicionales. Agregue cinco métodos adicionales de tal manera que el script tenga este aspecto:

@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 overloaded so it returns 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.

Escena de pantalla inicial

Cree una nueva escena con un nodo raíz derivado de ''Control'' (para este plugin de ejemplo, haremos que el nodo raíz sea un ''CenterContainer''). Seleccione este nodo raíz, y en el Viewport, haga clic en el menú ''Layout'' y seleccione ''Completo''. También debe habilitar el indicador de tamaño vertical ''Expandir'' en el inspector. El panel ahora utiliza todo el espacio disponible en la ventana gráfica principal.

A continuación, agreguemos un botón a nuestro complemento de pantalla principal de ejemplo. Agregue un nodo Botón y establezca el texto en "Imprimir Hola" o similar. Agregue un script al botón como este:

@tool
extends Button


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

Luego conecte la señal "presionada" a sí misma. Si necesita ayuda con las señales, consulte el artículo Usando Señales.

Hemos terminado con el panel de la pantalla principal. Guarde la escena como main_panel.tscn.

Actualizar el complemento de script (secuencia de comandos)

Necesitamos actualizar el script `` main_screen_plugin.gd '' para que el complemento instale nuestra escena del panel principal y la coloque donde debe estar. Aquí está el script del complemento completo:

@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")

Se agregaron un par de líneas específicas. `` MainPanel`` es una constante que contiene una referencia a la escena, y la instanciamos en main_panel_instance.

The _enter_tree() function is called before _ready(). This is where we instance 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.

La función `` _exit_tree () '' se llama cuando el complemento está desactivado. Si la pantalla principal aún existe, llamamos a `` queue_free () '' para liberar la instancia y eliminarla de la memoria.

The _make_visible() function is overridden to hide or show the main panel as needed. This function is automatically called by the editor when the user clicks on the main viewport buttons at the top of the editor.

The _get_plugin_name() and _get_plugin_icon() functions control the displayed name and icon for the plugin's main viewport button.

Otra función que puede agregar es la función `` handle () '', que le permite manejar un tipo de nodo, enfocando automáticamente la pantalla principal cuando se selecciona el tipo. Esto es similar a cómo al hacer clic en un nodo 3D se cambiará automáticamente a la ventana gráfica 3D.

Prueba el plugin

Active el complemento en la Configuración del proyecto. Observará un nuevo botón junto a 2D, 3D, Script encima de la ventana principal. Al hacer clic en él, accederá a su nuevo complemento de la pantalla principal y el botón del medio imprimirá el texto.

Si quieres probar la versión terminada de este plugin, revisa las demos de plugins aquí: https://github.com/godotengine/godot-demo-projects/tree/master/plugins

Si desea ver un ejemplo más completo de lo que son capaces de hacer los complementos de la pantalla principal, consulte los proyectos de demostración 2.5D aquí: https://github.com/godotengine/godot-demo-projects/tree/master/misc/2.5d