Minecraft Wiki

LEE MÁS

Minecraft Wiki
Advertisement

Plantilla:Traducción en proceso

Para el comando, véase Comandos/function.
Véase también: Función (Bedrock Edition)
Information icon
Esta característica es exclusiva de Java Edition. 

Las Funciones permite a los jugadores hacer correr listas de comandos usando archivos de texto con la extensión .mcfunction. Se recomienda utilizar codificación ANSI (sin BOM) para los archivos de funciones para prevenir cualquier problema. Esta página cubre cómo utilizar las funciones en Java Edition.

Uso

Para utilizar funciones, un archivo de texto [FUNCTION_NAME].mcfunction deberá ser colocado en la carpeta [WORLD_NAME]/datapacks/[DATA_PACK_NAME]/data/[NAMESPACE]/functions. Para ejecutar la función, utilice el nombre de función completo, que es [NAMESPACE]:[FUNCTION_NAME]. Si no hay ambigüedad con otros paquetes de datos o con un comando de Minecraft existente, puedes usar [FUNCTION_NAME]. Si el espacio de nombres se omite al intentar llamar a una función, se establecerá de manera predeterminada en el espacio de nombres minecraft:. Se recomienda usar un espacio de nombres personalizado para evitar un comportamiento no deseado en el caso de futuras adiciones al espacio de nombres predeterminado.[1]

Las funciones también se pueden colocar en subcarpetas dentro de la carpeta functions. También es necesario tener un archivo pack.mcmeta en la carpeta [DATA_PACK_NAME]. Por ejemplo, ejecutar la función custom:example/test hará referencia al archivo ubicado en data/custom/functions/example/test.mcfunction.

Las funciones, al ser archivos de texto, son fácilmente modificables y es menos probable que los bloques de comandos induzcan retrasos cuando se usan en grandes cantidades. Si se modifica o agrega una función, usar el comando /reload recargará los archivos de función desde el disco. Esto permite que Minecraft reconozca cualquier cambio en los archivos de funciones, sin necesidad de salir y volver a entrar al mundo.

Upon successfully running /function, a message will display in the chat: Executed [amount] command(s) from function '[function file directory]'. Embedded functions won't display this chat messsage. The successful output of the commands inside a function cannot be measured with a comparator (although the same effect could be accomplished with the use of /execute store command).

In a singleplayer or a LAN world, like a command block, a function can run any command that is no more restrictive than permission level 2.

On the default multiplayer software, a function can run any command that is no more restrictive than the permission level prescribed in function-permission-level setting in server.properties.

Sintaxis de la función

TestingFunctions

Probando el sistema de funciones. En esta función simple se utilizaron tres mensajes /tellraw y un comando /give.

Dentro del archivo .mcfunction, se coloca un comando válido por línea, sin la barra inclinada habitual (/). Los jugadores pueden agregar comentarios dentro del archivo de texto de función comenzando una línea con #.

Los comandos individuales en las funciones pueden tener más de 32 500 caracteres como límite en los bloques de comandos, pero la cantidad total de comandos que se ejecutan dentro de una función seguirá obedeciendo a /gamerule maxCommandChainLength, que es 65 536 comandos de forma predeterminada; cualquier comando más allá de este límite será ignorado.

Ejecutando una función

Las funciones ejecutarán todos sus comandos en un solo tick y las funciones llamadas desde dentro de otras funciones también ejecutarán sus comandos en el mismo tick que su padre. Las funciones utilizarán el entorno de comandos de lo que sea que haya llamado a la función. Esto incluye el remitente del comando, la posición, la rotación, etc. Este contexto de comando se conserva para todos los comandos de la función, por lo que un comando /setblock utilizará el contexto de posición guardado incluso cuando un comando anterior en la misma función se teletransportó el albacea original a una posición diferente. Por ejemplo:

execute as @a at @s run function foo:bar

foo:bar

teleport @s ~ ~5 ~
setblock ~ ~-1 ~ emerald_block
execute at @s run setblock ~ ~-1 ~ diamond_block

When called through a player this function will teleport that player 5 blocks up, place an emerald block one block below their original position before the teleport, and place a diamond block one block below their new position after the teleport.

As seen in the above example, the command context can be updated as usual by their respective /execute sub-commands.

It is suggested to use @s target selector for the most frequently used entity in a function and use /execute as when calling that function to modify the executor entity to that most frequently used entity. This can simplify content if the entity was selected with target selector arguments and improve performance in general for the reduced iteration through the world entity list.

There are several methods of running a function file in-game:

Commands

/function
  • Allows players to run a function or all functions in a function tag once.
  • Uses the command environment of whatever called the /function command.
  • Initial command environment may be modified by the /execute command.
  • Usage: /function <name>

Advancements

Advancements can run a function once as a reward for completing them. The commands in the function are run through the player who completed the advancement.

Reward functions are called within advancement JSON files using the following format:

{
    "rewards": {
        "function": "namespace:path/to/function/file"
    }
}

Tags

Functions can be grouped together using tags in data packs. These tags can then be called to run all the functions inside that tag with /function #(namespace):(tag).

Functions tagged in tick will automatically run every tick at the beginning of the tick. Functions tagged in load will run after (re)loading the datapack.

  • Note: tick will run before load after reloading the datapack. This means that you can't inherently rely on a stable state of the datapack for the first tick.

Historial

Java Edition
1.12pre1Added functions.
pre3Commands are no longer allowed to begin with a / (forward slash)
Comments can now only be preceded with #; using // is no longer allowed
pre4Added new arguments to the /function command: [if|unless] [selector]
pre6Skipped functions (when a conditional fails) are now considered failures when used in commands.
1.1317w43aCustom functions have been moved into data packs.
17w45aFunctions are now completely parsed and cached on load.
17w49bRemoved /gamerule gameLoopFunction.
Function can now be tagged.
Functions tagged in tick now run every tick in the beginning of the tick.
18w01aFunctions tagged in load now run after (re)loading the datapack.
1.14.4pre4Added function-permission-level to server.properties

Issues

Los problemas relacionados con "función (java edition)" se mantienen en el rastreador de problemas.

Informa en esta página sobre los errores que encuentres (en inglés).

Referencias

Advertisement