Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Creando plugins

Acerca de los plugins

Un plugin es una gran manera de ampliar el editor con herramientas útiles. Se puede hacer completamente con GDScript y escenas estándar, sin siquiera recargar el editor. A diferencia de los módulos, no es necesario crear código C++ ni recompilar el motor. Aunque esto hace que los plugins sean menos potentes, todavía hay muchas cosas que puedes hacer con ellos. Ten en cuenta que un plugin es similar a cualquier escena que ya puedas hacer, excepto que se crea usando un script para añadir funcionalidad de edición.

This tutorial will guide you through the creation of two plugins so you can understand how they work and be able to develop your own. The first is a custom node that you can add to any scene in the project, and the other is a custom dock added to the editor.

Creando un plugin

Antes de empezar, crea un proyecto vacío nuevo donde quieras. Esto servirá como base para desarrollar y probar los plugins.

Lo primero que necesita el editor para identificar un nuevo plugin es crear dos archivos: un plugin.cfg para la configuración y un script de herramientas con la funcionalidad. Los plugins tienen una ruta estándar como addons/plugin_name dentro de la carpeta del proyecto. Godot proporciona un diálogo para generar esos archivos y colocarlos donde deben estar.

In the main toolbar, click the Project dropdown. Then click Project Settings.... Go to the Plugins tab and then click on the Create New Plugin button in the top-right.

Verás aparecer el diálogo, así:

../../../_images/making_plugins-create_plugin_dialog.webp

El texto del marcador de posición en cada campo describe cómo afecta a la creación de los archivos del plugin y a los valores del archivo de configuración.

Para continuar con el ejemplo, utiliza los siguientes valores:

Plugin Name: My Custom Node
Subfolder: my_custom_node
Description: A custom node made to extend the Godot Engine.
Author: Your Name Here
Version: 1.0.0
Language: GDScript
Script Name: custom_node.gd
Activate now: No

Advertencia

Desactivar la opción ¿Activar ahora? en C# siempre es necesario porque, al igual que cualquier otro script de C#, el script EditorPlugin necesita ser compilado, lo que requiere construir el proyecto. Después de construir el proyecto, el complemento puede ser habilitado en la pestaña Plugins de Configuración del Proyecto.

Feberías terminar con una estructura de directorios como esta:

../../../_images/making_plugins-my_custom_mode_folder.webp

plugin.cfg is an INI file with metadata about your plugin. The name and description help people understand what it does. Your name helps you get properly credited for your work. The version number helps others know if they have an outdated version; if you are unsure on how to come up with the version number, check out Semantic Versioning. The main script file will instruct Godot what your plugin does in the editor once it is active.

El archivo del script

Upon creation of the plugin, the dialog will automatically open the EditorPlugin script for you. The script has two requirements that you cannot change: it must be a @tool script, or else it will not load properly in the editor, and it must inherit from EditorPlugin.

Advertencia

In addition to the EditorPlugin script, any other GDScript that your plugin uses must also be a tool. Any GDScript without @tool imported into the editor will act like an empty file!

It's important to deal with initialization and clean-up of resources. A good practice is to use the virtual function _enter_tree() to initialize your plugin and _exit_tree() to clean it up. Thankfully, the dialog generates these callbacks for you. Your script should look something like this:

@tool
extends EditorPlugin


func _enter_tree():
    # Initialization of the plugin goes here.
    pass


func _exit_tree():
    # Clean-up of the plugin goes here.
    pass

Esta es una buena plantilla para usar cuando se crean nuevos plugins.

Un nodo personalizado

A veces queremos un cierto comportamiento en muchos nodos, como una escena personalizada o o un control que pueda ser reutilizado. Instanciarlo es útil en muchos casos, pero a veces puede ser incómodo, especialmente si lo está usando en varios proyectos . Una buena solución es crear un plugin que agregue un nodo con un comportamiento personalizado.

Advertencia

Los nodos agregados vía EditorPlugin, son nodos "CustomType". Cuando estos trabajan con algún lenguaje de scripting, tienen menos características que the Script Class system. Si usted está escribiendo Gdscript o NativeScript, recomendamos usar Script Classes en su lugar.

To create a new node type, you can use the function add_custom_type() from the EditorPlugin class. This function can add new types to the editor (nodes or resources). However, before you can create the type, you need a script that will act as the logic for the type. While that script doesn't have to use the @tool annotation, it can be added so the script runs in the editor.

For this tutorial, we'll create a button that prints a message when clicked. For that, we'll need a script that extends from Button. It could also extend BaseButton if you prefer:

@tool
extends Button


func _enter_tree():
    pressed.connect(clicked)


func clicked():
    print("You clicked me!")

That's it for our basic button. You can save this as my_button.gd inside the plugin folder. You'll also need a 16×16 icon to show in the scene tree. If you don't have one, you can grab the default one from the engine and save it in your addons/my_custom_node folder as icon.png, or use the default Godot logo (preload("res://icon.svg")).

Truco

SVG images that are used as custom node icons should have the Editor > Scale With Editor Scale and Editor > Convert Icons With Editor Theme import options enabled. This allows icons to follow the editor's scale and theming settings if the icons are designed with the same color palette as Godot's own icons.

../../../_images/making_plugins-custom_node_icon.png

Ahora, debemos agregarlo como un tipo personalizado para que se muestre en el cuadro de diálogo Crear nuevo nodo. Para eso, cambie el script custom_node.gd a lo siguiente:

@tool
extends EditorPlugin


func _enter_tree():
    # Initialization of the plugin goes here.
    # Add the new type with a name, a parent type, a script and an icon.
    add_custom_type("MyButton", "Button", preload("my_button.gd"), preload("icon.png"))


func _exit_tree():
    # Clean-up of the plugin goes here.
    # Always remember to remove it from the engine when deactivated.
    remove_custom_type("MyButton")

Una vez hecho esto, el complemento ya debería estar disponible en la lista de complementos en Configuración del proyecto, así que actívelo como se explica en Verificación de los resultados.

Luego pruébalo y agregando tu nuevo nodo:

../../../_images/making_plugins-custom_node_create.webp

Cuando agrega el nodo, puede ver que ya tiene adjunto el script que creó. Establezca un texto para el botón, guarde y ejecute la escena. Al hacer clic en el botón, puede ver un texto en la consola:

../../../_images/making_plugins-custom_node_console.webp

Un panel personalizado

Algunas veces necesitarás ampliar el editor y añadir herramientas que estén siempre disponibles. Una forma fácil de hacerlo es añadir un nuevo panel con un plugin. Los paneles son sólo escenas basadas en Control, estas son creadas de una manera similar a las escenas GUI comunes.

La creación de un muelle personalizado se realiza como un nodo personalizado. Cree un nuevo archivo plugin.cfg en la carpeta``addons/my_custom_dock``, luego agregue el siguiente contenido:

[plugin]

name="My Custom Dock"
description="A custom dock made so I can learn how to make plugins."
author="Your Name Here"
version="1.0"
script="custom_dock.gd"

Luego cree el script custom_dock.gd en la misma carpeta. Rellénelo con la plantilla que hemos visto antes de para comenzar bien.

Dado que estamos intentando añadir un nuevo panel personalizado, necesitamos crear el contenido de dicho panel. Esto no es más que una escena estándar de Godot. sólo crea una nueva escena y luego editarla.

Para un panel del editor, la raíz de la escena debe ser un Control o una de sus clases derivadas. Para este tutorial, puedes hacer un solo botón. El nombre del nodo raíz también será el nombre que aparezca en la pestaña del panel, así que asegúrate de poner uno descriptivo pero corto. No olvides añadir un texto a tu botón.

../../../_images/making_plugins-my_custom_dock_scene.webp

Guarda la escena como my_dock.tscn. Ahora necesitas seleccionar la escena que creaste y añadirla como un panel en el editor. Para ello puedes usar la función add_control_to_dock() de la clase EditorPlugin.

Necesitas seleccionar una posición de panel para añadirlo y tener un Control para añadir (que es la escena que acabas de crear). No olvides quitar el panel cuando el plugin es desactivado. El código debería verse así:

@tool
extends EditorPlugin


# A class member to hold the dock during the plugin life cycle.
var dock


func _enter_tree():
    # Initialization of the plugin goes here.
    # Load the dock scene and instantiate it.
    dock = preload("res://addons/my_custom_dock/my_dock.tscn").instantiate()

    # Add the loaded scene to the docks.
    add_control_to_dock(DOCK_SLOT_LEFT_UL, dock)
    # Note that LEFT_UL means the left of the editor, upper-left dock.


func _exit_tree():
    # Clean-up of the plugin goes here.
    # Remove the dock.
    remove_control_from_docks(dock)
    # Erase the control from the memory.
    dock.free()

Tenga en cuenta que, si bien el muelle aparecerá inicialmente en su posición especificada, el usuario puede cambiar libremente su posición y guardar el diseño resultante.

Comprobando los resultados

It's now time to check the results of your work. Open the Project Settings and click on the Plugins tab. Your plugin should be the only one on the list.

../../../_images/making_plugins-project_settings.webp

You can see the plugin is not enabled. Click the Enable checkbox to activate the plugin. The dock should become visible before you even close the settings window. You should now have a custom dock:

../../../_images/making_plugins-custom_dock.webp

Ir más allá

Ahora que ha aprendido a como crear complementos básicos, puede ampliar el editor de varias formas. Se pueden agregar muchas funciones al editor con GDScript; es una forma poderosa de crear editores especializados sin tener que profundizar en los módulos de C ++.

Puede crear sus propios complementos para ayudarse a sí mismo y compartirlos en la Biblioteca de activos <https://godotengine.org/asset-library/> _ para que las personas puedan beneficiarse de su trabajo.

Registrando autoloads/singletons en plugins

Es posible que los plugins del editor se registren automáticamente autoloads cuando el plugin está habilitado. Esto incluye también la des-registración del autoload cuando el plugin está deshabilitado.

Esto agiliza la configuración de los plugins para los usuarios, ya que ya no tienen que añadir manualmente los autoloads a la configuración de su proyecto si el plugin del editor requiere el uso de un autoload.

Utiliza el siguiente código para registrar un singleton desde un plugin del editor:

@tool
extends EditorPlugin

# Replace this value with a PascalCase autoload name, as per the GDScript style guide.
const AUTOLOAD_NAME = "SomeAutoload"


func _enter_tree():
    # The autoload can be a scene or script file.
    add_autoload_singleton(AUTOLOAD_NAME, "res://addons/my_addon/some_autoload.tscn")


func _exit_tree():
    remove_autoload_singleton(AUTOLOAD_NAME)