Skip to content

Translation notice

This page was translated with machine translation and may contain inaccuracies. If you can help improve it, please open an issue or submit a pull request.

A brief introduction to data pack and a guide

TIP

This article is a quick introduction for readers with programming foundation and experience.

If you don’t have any foundation, please read Recommended Reading for Zero Basics

Configure work environment

Minecraft

First, you need to get the Minecraft game first. Although the data pack was added in version 1.13, we strongly recommend that you use the latest official version when you first get started. If nothing else, this article will be maintained according to the current highest version.

Minecraft Wiki contains a wealth of important reference information, which in most cases also applies to the latest version.

At the same time, although the data pack is compatible with mods in most cases, we strongly recommend that you use vanilla games when you first get started to avoid problems that may be caused by mods.

VS Code

Although there are some other projects that provide data pack development environments under development or testing, the current mainstream solution is still to use VS Code and the following plug-ins:

  • Datapack Helper Plus by Spyglass
    • Referred to as "Spyglass", "DHP", or "Dahanpi".
    • Provides intelligent completion, error correction, coloring and other IntelliSense support for data pack and resource pack.
    • spgoding.datapack-language-server
  • Mcdoc Syntax Highlighting
    • mcdoc language support. This is a non-myworld official Schema file.
    • Dahanbatch can read mcdoc files to provide customized completion and error correction for the dictionary-style custom structure of data pack.
    • misodee.vscode-mcdoc
  • NBT Viewer
    • supply.nbtFile viewing and modification functions.
    • nbtIt is the main format used by Minecraft archives to store terrain, world settings, world data, etc.
    • misodee.vscode-nbt

When Dahanbatch is used, it will connect to its server that is not in mainland China to download some data. In mainland China, sometimes the download fails due to network problems, resulting in the plug-in not being able to be used normally (such as a large number of hits, no completion, etc.).

If you encounter this problem and don't know how to solve it, try joining on this page for help in any QQ group chat.

Create your first project

The data pack needs to be installed separately for each world and therefore is not globally effective. To create a new data pack, first create a new world in the game.

When creating a world, be sure to turn on the "Allow command" option. Although this option does not affect the use of data pack, it can facilitate your debugging.

In game, press/Open the chat bar and enter command

mcfunction
/datapack create mypack example_datapack

The game will create a new one for you in the current world, namedmypackdata pack.

Now open the game save folder and clickdatapacksfolder, your data packmypackJust lie inside and open it with VS Code.

data pack infrastructure

The root directory of the data pack has apack.mcmetafile.

This file contains basic information about this package, such as applicable Minecraft version number and description. The game also identifies different versions of data packs by finding and reading this file.

exist26.1.2When using the method above to create a data pack, itspack.mcmetaIt should look like this:

json
{
  "pack": {
    "description": "example_pack",
    "min_format": [
      101,
      1
    ],
    "max_format": 101
  }
}

indescriptionIt is the display description information of the data pack and can be modified arbitrarily.min_formatandmax_formatThey are the highest and lowest data versions compatible with this data pack respectively.pack.mcmetaThe detailed structure of can be read by reading wiki page, but you don't need to modify it for this getting started.

The structure of the resource pack will not be detailed in this brief description, but it has a meta-information file that is very similar to the data pack.

File organization

There are strict restrictions on file naming in data packs. All file and folder names must use lowercase letters only[a-z],number[0-9], underline_, hyphen`

  • , and dot.`。

The different symbols in the data pack are managed entirely through the folder structure. Each file represents an independent, "indivisible" object. For example, you cannot create multiple functions in one file. On the contrary, each.mcfunctionThe file declares a new, independent function.

Similar to C++, data pack uses a namespace structure. Two different ones from different namespacesstartfunction or JSON configuration files can exist at the same time and are identified asnamespace_1:startandnamespace_2:start

The general file structure of data pack is as follows:

  • pack.mcmeta: metadata file
  • data:Folder containing allmcfunctionorjsondocument.
    • <namespace>:namespace folder. any namespace of yours. Everything in this folder will become part of this namespace.
      • function:function folder. Create arbitrary functions inside
        • <your_function>.mcfunction: A function that can nest more folders.
      • <JSON配置项名>: The name of a game registry, for exampleadvancementRepresents advancement,recipeRepresents synthesis recipe.
        • <your_config>.json: A new entry to the registry, or overwriting an existing entry.

Want to refer to a person located infooin namespacebar.mcfunctionfunction file, use it directlyfoo:bar. likebarplaced in an additionaldirfolder, thenfoo:dir/bar. The same goes for JSON files. This form is called namespaceID.

You may find that since namespaceID does not contain the type of the target, abar.mcfunctionfunction file and any registrybar.jsonConfiguration files have the same namespaceIDfoo:bar. This is normal because any place that requires a namespaceID also knows what target it requires.

your first function

Now, create a folder in the root directory based on the file structure abovedata, create your namespace folder in it, we will usetutorial

existtutorialCreate folder infunction, where the first file is createdhello_world.mcfunction

onemcfunctionThe file consists of arbitrary commands, each command occupies one line. When the function is executed, the game will execute each command in sequence from top to bottom.

If the first non-whitespace character of a line is#, this line is treated as a comment.

It is somewhat similar to assembly. Minecraft provides you with a series of instructions, each of which can only complete a simple operation, such as changing the block at the specified coordinate, generating a mob at the specified coordinate, or manipulating variables to perform simple size comparisons or four arithmetic operations.

Similar to the terminal command line of most operating systems, each command has a command header, followed by several parameters separated by spaces.

For examplesaycommand can print messages in the chat bar:

mcfunction
say <消息>

&lt;消息>It is a greedy string and can be any text.

In the first line of your function write:

mcfunction
say Hello, World!

Save, the first function is completed.

Reload data pack and execute function

Back in the game, although you have created your first function, the data pack is not loaded in real time. In addition to the data pack being automatically loaded once when the server is restarted (such as exiting and re-entering the world), whenever the contents of the data pack change, the data needs to be reloaded manually.

To reload, press/Call out the chat bar and enter

mcfunction
/reload

Just press Enter to execute. Reload itself is also a command and can be written into a function (although it is not recommended). In fact, you can execute any command that can be executed in the chat bar by adding/Just to distinguish normal chat messages (but the effect of this may not be the same!).

Now your function should be loaded. If you want to execute any function, you can use commandfunction

mcfunction
function <命名空间ID>

So, try executing your function:/function tutorial:hello_world

Of course, there are many other ways to execute a function besides executing it manually. For example, it is triggered by various monitoring, or triggered every moment, scheduled, etc., which will be discussed in detail later.

A brief introduction to Mcfunction language

This chapter will introducemcfunctionlanguage logic to provide readers with some basic concepts and references. Wiki's command interface has detailed introductions to all commands and should be used as your primary reference. In addition, Vanilla Library's Reference page contains detailed tutorials for different commands.

statement control flow

returncommand can immediately end the execution of the current function. It can return any integer type;failyes0Syntactic sugar for:

mcfunction
say 你好
return 1
# 不会执行
say 再见
mcfunction
# 以下两条命令等价
return 0
return fail

return runYou can receive any command, execute the command and return the return value of the command.

mcfunction
# 执行本函数可以看到输出1和2,但是没有输出3
say 1
return run say 2
say 3
mcfunction
# 本函数会返回3,因为return run会返回被执行的命令的返回值。
return run return 3

Sorry,mcfunctionnothing similarforwhilejumpgotoThis class can change the way the next command is executed within the function. Function can only execute commands in order from top to bottom.

Therefore, all loops can only be implemented through recursion.

It's also a pity, althoughmcfunctionConditional judgment can be made, but due to lack of similargotoBecause of the command, branches cannot be made within the function.

executeIt is a very complex command used to change the execution context. One of its functions is to be connected in front of another command. The command will only be executed when a certain condition is passed, otherwise it will not be executed:

mcfunction
# 条件为真就执行<命令>
execute if <条件> run <命令>
# 条件为假就执行<命令>
execute unless <条件> run <命令>

Its conditional judgment can only limit this command. Regardless of whether it is passed or not, it cannot directly affect the subsequent command. If you need something similar to that in modern languagesif

  • else if
  • elseblock, you need to create 3 additional functions and match them with returncommand:
mcfunction
# 你的主函数
say do something
# 整个条件块独立为一个函数:
function tutorial:condition
say do some more thing
mcfunction
# 函数tutorial:condition

# 若条件成立,只执行if函数(内容省略)
execute if <条件> run return run function tutorial:condition/if
# 若上方条件不成立但下方条件成立,只执行else_if函数(内容省略)
execute if <条件> run return run function tutorial:condition/else_if
# 否则,只执行下面的else块
say else部分

Of course, in actual use it's rarely fully deployed like this. Many times there are simpler solutions.

variable

mcfunctionThere are no local variables or private variables at all. All variables are global and public and can be accessed and modified by anyone.

At the same time, the main logic of Minecraft is single-threaded, and the data pack is also part of the main logic. Therefore, you never need to worry about data contention problems caused by multi-threading.

There are two ways to save data commonly used in data pack:

scoreboard

The scoreboard can store any number of 32-bit signedint. You can perform basic operations on the data on the two scoreboards, including assignment, max, min, exchange, addition, subtraction, multiplication and division.

All operations have only two operations; this means that a single command is alwaysx += yform, and want to getx = y + zThe form requires multiple commands.

The scoreboard is a two-layer structure. If you want to store a value, you need to create a "score item" first. Each "goal" can have a different score on each scoreboard (imagine a literal scoreboard! The kind that hangs in a stadium). A goal and a score item together define a variable.

The goal can correspond to an entity in the game. For example, each player can have a score for each scoring item; the goal can also be completely virtual and not correspond to any entity.

Scoring items must be created before they can be used, but goals can be used directly without declaring them. The default value of the target on the score item (before it is assigned a value) is void. Any conditional judgment of greater than or less than it will not pass, but it will be assigned a value before it is used as an operation target.0

In addition, the ID of the scoring item is a rare object in the data pack that does not have the concept of namespace. If you need to ensure compatibility, you can only use prefix and suffix distinction.

The command to manage scoreboard isscoreboard. relatedscoreboardFor detailed syntax of command, please see wiki, or check the tutorials in the library

mcfunction
# 创建ID为tutorial的新计分项
scoreboard objectives add tutorial dummy
# 赋值 x@tutorial = 1
scoreboard players set x tutorial 1
# 创建ID为example的新计分项
scoreboard objectives add example dummy
# 赋值 x@example = 3
scoreboard players set x example 3
# 赋值 x@example += 5
scoreboard players add x example 5
# 赋值 y@tutorial = x@example
scoreboard players operation y tutorial = x example
# 计算 x@tutorial = max(x@tutorial, y@tutorial)
scoreboard players operation x tutorial > y tutorial
# 计算 x@exmaple *= x@tutorial
scoreboard players operation x example *= x tutorial
# return 0 if x@example >= 10
execute if score x example matches 10.. run return fail
# else return 1
return 1

Storage

Storage is a container with a dictionary structure similar to JSON, stored in NBT format (in fact, JSON can almost be said to be a subset of NBT,nullexcept). You can store any number of 8-bit, 16-bit, 32-bit, or 64-bit signed integers, single- and double-precision floating point numbers, and strings as key-value pairs, and you can arbitrarily nest dictionaries and lists to organize them.

Sounds wonderful? However, no calculations can be performed directly on the values ​​stored in Storage. To calculate, either first convert them asintCopy the form into the scoreboard, store it back after calculation, or use other special black technologies.

Although Storage has computational limitations, it is capable of storing complex data in complex structures. In addition, there are many objects in Minecraft (namely entities and blockentities) that have their own data, which are stored in the same format as Storage. This data can be copied into Storage for manipulation or storage...so Storage is actually extremely important.

Storage uses namespace format and can be used directly without declaration. it usesdataCommand operations can perform data reading, overwriting, copying, dictionary merging, list insertion, deletion, and simple string conversion and cutting. For details, see Wiki and Tutorials in the Library

mcfunction
# 把tutorial:example的dict赋值为一个包含了各种数据类型的字典。数字后的字母后缀表示了它的数据类型。
data modify storage tutorial:example dict set value {int:1, short:1s, byte:1b, long:1L, float:1.0f, double:1.0d, string:"Hello World!", list:[1,2,3,4,5], child:{more_data:[1,2,3,4,5]}}
# 读一下int的数值(虽然既没有打印也没有存到其他地方)
data get storage tutorial:example dict.int
# 使用索引读一下child里面的列表的第3项:
data get storage tutorial:example dict.child.more_data[2]
# 自从1.21.5以后,列表均为异构列表,因此这里我们可以给list最后插入一个字典。
data modify storage tutorial:example dict.list append value {data:{answer:42}}
# 删掉double
data remove storage tutorial:example dict.double
# 把long复制一份存进copy:
data modify storage tutorial:example copy set from storage tutorial:example dict.long
# 把string截取前5个字符存进stem:
data modify storage tutorial:example stem set string storage tutorial:example dict.string 0 4
# 把list的所有元素都塞到more_data的最前面:
data modify storage tutorial:example dict.child.more_data prepend from storage tutorial:example dict.list[]
# 最后返回short的数值
return run data get storage tutorial:example dict.short

entity and selector

In addition to blocks, game objects in Minecraft also include entities. Entities are not locked in the grid like blocks. They have their own data and will be tracked and updated by the game every moment. Players, various mobs and monsters, and even armor stands, arrows, fireballs, etc. are all entities.

There are many commands that require passing in an entity as the target, such as killcommand, which can kill an entity:

mcfunction
kill <目标>

If you want to pass in the entity, if you cannot hardcode the target ID in the data pack, you can only use the selector. A selector is something that finds one or more entities in the world based on conditions at runtime.

For example, selector@aAll players will be selected,@nThe entity closest to the execution location will be selected.@rA random player will be selected. thereforekill @acommand will kill all players,kill @nwill kill the nearest entity, andkill @rWill kill a random player.

Apart from@A simple form followed by a letter, and various conditions can be added at the end for fine-grained filtering.

Most of the commands mentioned above can use selectors, for example:

mcfunction
# 将所有玩家在tutorial上的分数设为1
scoreboard players set @a tutorial 1
# 给随机玩家在tutorial上的分数加1
scoreboard players add @r example 1
# 杀死所有tutorial上的分数小于等于1的玩家
kill @a[scores={tutorial=..1}]

For details, see the introduction to selectors in the Wiki and this library.

The use of entities is one of the cores of the data pack project. entity can besummoncommand is created,killcommand delete,tpcommand moves,dataCommands read, modify, and store data, which can also have their own scores on the scoreboard, etc. Using entities makes it easy to record coordinates, situations, tracking status, etc. over long periods of time. Minecraft even offers a dedicated标记entity can complete the above work with almost no performance consumption. It is no exaggeration to say that the use of entities is as core as variables, control flow, etc. in data pack.

function macro

Unless a command specifically allows it, you can't pass variables to the command, you can only hardcode them. The macro lines that appeared after 1.20.2 solved this problem at a certain performance cost. It allows you to use macros to "assemble" a command at runtime, and the game is loaded and executed in real time. I won’t discuss it in detail here, but you can read Wiki’s functioninterface.

Error handling

mcfunction has no built-in error handling at all, and certainly nothing liketryexceptcatchStatements like that. Any command will never report an error. Any errors that may occur will simply fail silently and continue to the next step, leaving at most a warning message in the log.

For commands that may fail (such as trying to use a selector to find an entity that may not exist), if the failure situation needs to be handled, it must be explicitly checked by the writer.

If there is a syntax problem with the function, or the content of the JSON configuration file is illegal, the file will not be loaded when loading. This failure will only leave a message in the log. If there is an error parsing the function macro at runtime, the entire function will not be executed.

What should I do next?

Check out the Wiki and this library for more commands!

Commands are like instructions in assembly. You should gradually review, test, and use different commands until you know this "data pack instruction set" well!

Wiki's command interface has a detailed introduction to all commands. In addition, Vanilla Library's Reference page contains detailed tutorials for different commands. The Vanilla Library also has a large number of pages dedicated to various aspects of the command system.

Check out the registry JSON file!

These files are not covered in this brief description, but they are very important! For example, you can register predicate to be called in command to implement complex condition detection, and add function tominecraft:tickfunctiontag to make it execute every moment, or register new spells to serve logic or gameplay, or even register new dimensions and new mob groups independent of the main world, the nether, and the end!

Wiki's data pack interface will tell you everything that can be registered.

Play with the resource pack!

Relying only on data pack, the expression ability is somewhat limited. Resource packs can add custom textures, models, fonts, etc., greatly expanding the possibilities. In conjunction with data pack, various black technologies can be developed, which Mojang probably didn’t expect to be able to do!

Make a small project!

The best way to grow is not to read hard, but to try to make a small gadget yourself, and then look up the information to try to solve the difficulties encountered.

See examples!

Find other people's projects or tutorials in this library, monthly magazine, and Bilibili. How do they use simple commands to combine various effects?

Ask for help!

Don’t do things behind closed doors! Since the Chinese Internet lacks a unified forum, many technical discussions are scattered in QQ groups. Go to this page Find a few groups to join. Even if you don't speak, just watching other peoplediscussing can also benefit a lot.

The most important thing...

Have fun! Minecraft is a game, and so is data pack. Every author is a player first before being a developer. Have fun!

Powered by VitePress and GitHub Pages