Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 23 — Functional Components: Food, Tools, Weapons, and Armor

What You’ll Build

In Chapter 21 you learned what data components are: the named pieces of data stamped onto every item, written in square brackets after the item’s ID like iron_sword[custom_data={foo:1}]. Most of the components you’ve met so far have been about how an item looks or reads: its name, its lore, its custom model. This chapter is about the other half, the components that change how an item behaves.

By the end of this chapter you’ll be able to make almost any item act like almost any other kind of gear. You’ll turn a plain item into food with your own nutrition and a built-in effect; give a tool custom mining rules; turn an item into a weapon, or even into a shield that blocks attacks; make an item wearable in an armor slot; pile stat bonuses onto it; and control its whole durability life: how much it can take, whether it can be enchanted, and what repairs it. You’ll also meet three brand-new components from the 26.x updates: glider (elytra-style flight on any item), kinetic_weapon (charge/ram attacks), and death_protection (a totem’s “save you once” behavior, now data-driven).

To finish, you’ll write one function, mypack:make_items, that hands you three custom items: a snack that grants Night Vision, a pickaxe that rips through stone, and a pair of boots that make you run faster. This chapter extends the mypack pack you started in Chapter 9 and uses the test world from Chapter 1.

Behavior lives in components too

Quick recap of the rule from Chapter 21. In a command like /give, an item is written as item_id[component=value,component=value]: the item’s ID, then its data components listed in square brackets. You can also remove a component an item normally has by putting ! in front of it: item_id[!component]. Anything you don’t list keeps the item’s normal default.

There’s an important line to draw here. Data components cover most of an item’s characteristics, but not all: some behavior is hardwired to the item ID itself and cannot be removed from the item, nor applied to a different item that does not have that behavior by default. So components have limits: you can give a stick a food component and eat it, but you can’t, say, give a stick the exact built-in shooting behavior of a bow just by adding a component. Keep that boundary in the back of your mind; almost everything in this chapter works on almost any item, but a few item behaviors stay fixed.

One more reminder about where we’ll write these commands. Following our rule from Chapter 9, every command goes inside a .mcfunction file with no leading slash, and we run the file with /function. When this chapter shows a command on its own to explain a single component, picture it as one line of such a file.

Food and consuming: build a Night Vision snack

Two components work together to make an item edible: food and consumable.

The food component is a functional component that holds the food stats applied when the item is eaten. It has exactly three fields:

  • nutrition: an integer, the number of food points (the drumsticks on your hunger bar) restored when the player eats it. Must be zero or more.
  • saturation: a number (it can have a decimal), the amount of saturation restored. Saturation is the hidden reserve that keeps your hunger bar from dropping right away.
  • can_always_eat: true or false. If true, the item can be eaten even when your hunger bar is full. Defaults to false.

A simple example is a custom melon slice:

give @s melon_slice[food={nutrition:3,saturation:1,can_always_eat:true}]

That gives “a melon slice that can be eaten at any time and restores 3 food points and 1 saturation.”

On its own, though, food mostly just records stats. To actually control the act of eating (how long it takes, what sound and animation it uses, and what happens the moment you finish) you add the consumable component. If consumable is present, the item can be consumed on use, and if a food component is also present, eating it applies that food’s stats. Its fields:

  • consume_seconds: a number, how many seconds it takes to consume. Defaults to 1.6.
  • animation: which use-animation plays. Must be one of: none, eat, drink, block, bow, spear, crossbow, spyglass, toot_horn, brush, bundle, or trident. Defaults to eat.
  • sound: the sound event played while consuming. Defaults to entity.generic.eat.
  • has_consume_particles: true or false, whether the little munching particles fly out. Defaults to true.
  • on_consume_effects: an optional list of consume effects that fire as a result of eating it.

That last field is where the work happens. A consume effect is one entry describing something that should happen when the item is consumed. The kinds are named in its type field: apply_effects, remove_effects, clear_all_effects, teleport_randomly, and play_sound. For our snack we want apply_effects, which applies status effects to whoever ate it. When the type is apply_effects, these extra fields apply:

  • effects: a list of effect instances. Each one is an object with:
    • id: the ID of the effect, e.g. minecraft:night_vision.
    • amplifier: the strength, where level I is value 0. Optional, defaults to 0.
    • duration: how long, in ticks (20 ticks = 1 second). -1 means infinite. Optional, defaults to 1 tick.
    • plus optional display switches: ambient, show_particles, show_icon.
  • probability: the chance (0.0 to 1.0) the effects are applied. Defaults to 1.0.

Under the Hood (skippable). Here’s a consumable example that clears effects on eat: give @s gold_ingot[consumable={consume_seconds:3.0, animation:'eat', sound:'entity.generic.eat', has_consume_particles:true, on_consume_effects:[{type:'minecraft:clear_all_effects'}]}] This is “a gold ingot that can be eaten in 3 seconds and upon consuming, clears all effects.” Notice the effect’s type there is minecraft:clear_all_effects, which needs no extra fields. We’re using apply_effects instead, which does.

Now our snack. We’ll start from a cookie, make it grant Night Vision for 30 seconds (30 × 20 = 600 ticks) when eaten, and let it be eaten even on a full hunger bar:

give @s cookie[food={nutrition:4,saturation:2,can_always_eat:true},consumable={animation:'eat',on_consume_effects:[{type:'minecraft:apply_effects',effects:[{id:'minecraft:night_vision',duration:600}]}]}]

Eat it and your screen brightens for half a minute. The food component handles the 4 food points and 2 saturation; the consumable component’s on_consume_effects handles the Night Vision.

Modern Minecraft. In older tutorials you’ll see people fake custom food with command blocks that watch for an item being eaten, or with hardcoded item NBT. In current Minecraft the food is the data: the food and consumable components describe the whole behavior, and the game does the rest.

Figure (to be captured). a cookie tooltip in hand, and the same player eating it with the Night Vision screen brightening

Tools: a pickaxe that eats through stone

The tool component marks an item as a tool and spells out how it mines. Its fields:

  • default_mining_speed: a number, the mining speed used when no rule below overrides it. Defaults to 1.0. (A plain hand is 1.0; higher is faster.)
  • damage_per_block: an integer, how much durability is removed each time you break a block with it. Defaults to 1.
  • can_destroy_blocks_in_creative: true/false, whether you can break blocks holding it in Creative. Defaults to true.
  • rules: a list of special-case rules. The game reads them in order and the first matching rule wins. Each rule is an object with:
    • blocks: which blocks it applies to: a single block ID, a block tag written with a # (like #minecraft:mineable/pickaxe, meaning “every block a pickaxe is meant to mine”), or a list of block IDs.
    • speed: if the blocks match, the mining speed to use instead of the default. Optional.
    • correct_for_drops: if the blocks match, whether this tool counts as the correct tool: mining at full speed and actually dropping the block’s items. Optional, defaults to false.

Here’s an example that turns a humble fence into a pickaxe:

give @p oak_fence[max_stack_size=1,max_damage=350,damage=0,tool={default_mining_speed:1.5,damage_per_block:2,rules:[{blocks:"#mineable/pickaxe",speed:6,correct_for_drops:true}]}]

That “gives an oak fence that has the properties of a pickaxe”: speed 6 on anything in the pickaxe tag, and it drops what it mines. Notice it pairs tool with max_damage, damage, and max_stack_size so the fence has durability and stops stacking, just like a real tool. We’ll come back to those durability components at the end of the chapter.

For our practice item we’ll take a real diamond pickaxe and make it shred stone specifically, very fast:

give @s diamond_pickaxe[tool={default_mining_speed:1.0,rules:[{blocks:'minecraft:stone',speed:25,correct_for_drops:true}]}]

A rule with blocks:'minecraft:stone' and speed:25 means: when you hit stone, mine at speed 25 (far faster than a normal pickaxe), and because correct_for_drops is true, the stone still drops properly. Every other block falls back to default_mining_speed.

Weapons, reach, and shields

Now combat. This is where lots of outdated tutorials get it wrong, so read carefully. The real weapon component differs from what the old guides claim.

weapon — the fields that really exist

Here is the single most important correction in this chapter. The weapon component does not hold “attack damage” or “attack speed.” If present, the item is a weapon, but for attack damage you use the attribute_modifiers component. The weapon component itself has exactly two fields:

  • item_damage_per_attack: an integer, how much durability the item loses per attack. Defaults to 1.
  • disable_blocking_for_seconds: a number, how many seconds this weapon can disable a blocking shield when it lands a hit. If 0, it can’t disable shields. Defaults to 0.

For example:

give @p iron_sword[weapon={disable_blocking_for_seconds:5,item_damage_per_attack:10}]

This is “an iron sword that disables shields for 5 seconds when used on them, but loses 10 durability for each attack performed.” So weapon is about durability cost per swing and shield-breaking, not the damage number. Attack damage comes from attribute_modifiers, which we build later in this chapter.

Modern Minecraft. If a tutorial tells you to put attack_damage or attack_speed inside the weapon component, it’s describing a version that no longer matches the game. In current Minecraft, those numbers are attributes (next section on attribute_modifiers), and weapon only carries item_damage_per_attack and disable_blocking_for_seconds.

attack_range — how far your hit reaches

The attack_range component sets the melee reach of a weapon: how far the target can be and still count as hit. Its fields (all distances in blocks):

  • min_reach: minimum distance to count as a valid hit. Defaults to 0.0.
  • max_reach: maximum reach in Survival. Defaults to 3.0.
  • min_creative_reach: minimum in Creative mode. Defaults to 0.0.
  • max_creative_reach: maximum in Creative mode. Defaults to 5.0.
  • hitbox_margin: extra margin added to the target’s box when checking the hit. Defaults to 0.3.
  • mob_factor: a multiplier on the reach when a mob (not a player) uses the item. Defaults to 1.0.

So a long spear-like reach of 5 blocks is just:

give @s diamond_sword[attack_range={max_reach:5.0}]

blocks_attacks — turn any item into a shield

This is one of the headline new abilities: the blocks_attacks component lets any item be used like a shield. When present, the item can be used like a shield to block attacks to the holding player. Its fields:

  • block_delay_seconds: how long you must hold use before blocking kicks in. Defaults to 0.
  • disable_cooldown_scale: a multiplier on how long the item gets disabled when hit by a shield-disabling attack (that’s the disable_blocking_for_seconds from the attacker’s weapon component). If 0, this item can never be disabled. Defaults to 1.
  • damage_reductions: a list of rules for what and how much damage to block. Each rule is an object with:
    • type: a list of damage types to block (each written as a damage type id like mob_attack, or a #-prefixed damage type tag). Optional; defaults to all damage types.
    • base: a flat amount of damage to block. Required.
    • factor: the fraction of incoming damage to block (0.0 to 1.0). Required.
    • horizontal_blocking_angle: the widest angle (in degrees) between where you’re facing and the incoming attack that can still be blocked. Defaults to 90.
  • item_damage: an object controlling how much the item is damaged when it blocks:
    • threshold: minimum incoming damage before the item takes any. Defaults to 0.
    • base: flat item damage once the threshold is passed. Defaults to 0.
    • factor: fraction of the blocked damage applied to the item. Defaults to 1.5.
  • block_sound: sound event when an attack is successfully blocked. Optional.
  • disabled_sound: sound event when the item goes on its disabled cooldown. Optional.
  • bypassed_by: a damage type tag (#...) listing damage types that ignore the block entirely. Optional.

Coming in Chapter 36. Two of these fields (damage_reductions[].type and bypassed_by) name damage types: individually (like mob_attack), or as #-prefixed tags standing for a whole group (“all fire damage,” “all explosions”). Tags and damage types are a topic of their own; we cover them fully in Chapter 36. For now just know you can leave both fields off to block (or not bypass) everything.

Here’s an example that makes a sword block half of certain damage:

give @s diamond_sword[blocks_attacks={disable_cooldown_scale:0,damage_reductions:[{type:[mob_attack,arrow,explosion],base:0,factor:0.5}],block_sound:block.anvil.place}]

This is a diamond sword that blocks half the damage from mob attacks, arrows, and explosions, can’t be disabled (disable_cooldown_scale:0), and clangs like an anvil when it blocks.

Three new 26.x components: glide, charge, and cheat death

These three components are new in the 26.x updates and are worth meeting on their own.

glider — elytra wings on anything

The glider component, when present, allows living entities to glide (as with elytra) when equipped. It has no fields of its own: its value is just an empty object {}. The catch is that gliding only works while the item is equipped, so you pair it with the equippable component (coming up next). One detail worth knowing: if the glider item is damageable, it only works while its damage is below max_damage − 1, and every second of gliding tries to wear off one point of durability.

Here’s an example that makes a nether star into head-slot wings:

give @s nether_star[equippable={slot:"head"},glider={}]

This is “a nether star that can be equipped in the head slot, and if placed on the head, it allows the player to glide.”

kinetic_weapon — charge and ram attacks

The kinetic_weapon component enables a charge-type attack: while you’re using the item, the damage is dealt based on how fast you and your target are moving toward each other. The game’s own example item is the Copper Spear. Its fields:

  • delay_ticks: ticks of wind-up before the weapon becomes effective. Defaults to 0.
  • forward_movement: how far the item lunges out of your hand during the animation. Defaults to 0.0.
  • damage_multiplier: multiplier turning relative speed into damage. Defaults to 1.0.
  • damage_conditions: an object describing when the charge deals damage.
  • knockback_conditions: an object describing when it knocks the target back.
  • dismount_conditions: an object describing when it knocks a rider off their mount.
  • sound: optional sound event when the weapon is engaged.
  • hit_sound: optional sound event when it hits an entity.

Each of those three *_conditions objects shares the same shape:

  • max_duration_ticks: how long (in ticks, counted after the delay) the condition keeps being checked.
  • min_speed: minimum speed of the attacker (blocks per second, along where they’re looking). Optional, defaults to 0.0.
  • min_relative_speed: minimum relative speed between attacker and target. Optional, defaults to 0.0.

Here’s an example that builds a charge weapon out of an amethyst shard:

give @s amethyst_shard[kinetic_weapon={forward_movement:0.0,delay_ticks:20,damage_conditions:{max_duration_ticks:60},knockback_conditions:{max_duration_ticks:40},dismount_conditions:{max_duration_ticks:20},hit_sound:"block.amethyst_cluster.step"}]

This is a charge attack that arms after a 1-second delay (20 ticks), then can damage for 3 seconds, knock back for the first 2, and dismount for the first 1.

death_protection — a data-driven totem

The death_protection component is the totem-of-undying behavior, now something you can stamp on any item. If present, the item protects the holder from dying by restoring a single health point. It has one optional field:

  • death_effects: a list of consume effects (the same kind you used for the food) that fire when the item saves you.

Here’s an example that puts it on a nether star:

give @s nether_star[death_protection={death_effects:[{type:'minecraft:clear_all_effects'}]}]

This is “a nether star that protects the holder from death and removes all status effects from the holder.”

Wearable gear and stat bonuses: build the speed boots

equippable — make an item wearable

The equippable component lets an item be worn in an equipment slot. It has a lot of fields; the ones you’ll use most are:

  • slot: which slot it goes in. One of: head, chest, legs, feet, body, mainhand, offhand, or saddle.
  • equip_sound: sound event when you put it on. Defaults to item.armor.equip_generic.
  • asset_id: the resource location of an equipment model to draw when it’s worn (this points at a file under assets/<namespace>/equipment/<id>.json). If you leave it out, the item renders as itself (or, off the head slot, may not render at all).
  • allowed_entities: limits which entities can wear it. Defaults to all.
  • dispensable: whether a dispenser can equip it. Defaults to true.
  • swappable: whether right-clicking equips it into its slot. Defaults to true.
  • damage_on_hurt: whether it loses durability when the wearer is hurt. Defaults to true.
  • equip_on_interact: whether you can equip it onto a mob by pressing use on the mob. Defaults to false.

(There are also camera_overlay, can_be_sheared, and shearing_sound fields for special cases.)

Coming in Part VIII. The asset_id field points at a custom equipment model, which is a resource pack file — art, not behavior. We name it here so you recognize it, but building the model is a job for the resource-pack chapters in Part VIII. Our boots will simply behave like boots without custom art.

A first example equips a glass block on the head:

give @s glass[equippable={slot:"head",equip_sound:"block.glass.break",dispensable:true}]

attribute_modifiers — stacking stat bonuses

To make our boots actually do something, we need attribute_modifiers. Remember from the glossary that an attribute is a numeric property of a player or mob (like max health, movement speed, or attack damage) with a base value plus modifiers. The attribute_modifiers component is a list of modifiers the item applies while it’s equipped in the right slot. One rule is worth keeping in mind: if the item is not in the correct equipment slot, it has no effect, and the modifiers are removed the moment the item leaves that slot.

Each modifier in the list is an object with these fields:

  • id: a namespaced ID naming this modifier. It must be unique among modifiers of the same attribute (so two boots can’t both use the same id on the same stat).
  • type: the namespaced ID of the attribute to act on (this is which stat: movement speed, attack damage, and so on).
  • slot: which equipment slot the item must be in for the bonus to count: one of any, hand, armor, mainhand, offhand, head, chest, legs, feet, body, or saddle. Defaults to any (meaning any equipment slot, not any inventory slot).
  • operation: how the number is applied. One of:
    • add_value: add the amount straight to the stat.
    • add_multiplied_base: add a fraction of the base value.
    • add_multiplied_total: multiply the running total.
  • amount: the number used by the operation.
  • display: optional; controls how the bonus appears in the tooltip.

Here’s an example that grows the player with a scale modifier:

give @s stick[attribute_modifiers=[{type:"minecraft:scale",slot:"hand",id:"example:grow",amount:4,operation:"add_multiplied_base"}]]

This is “a stick that causes the player to grow 4x when holding it.” Notice the shape: a list, each entry with type (the attribute), slot, id, amount, and operation. We’ll follow that exact shape for our boots, but target movement speed instead of scale, and the feet slot instead of hand.

A note on attribute names. The example above uses the attribute minecraft:scale. The attribute for run speed is named minecraft:movement_speed and the one for melee damage is minecraft:attack_damage. These are the standard attribute IDs the attribute_modifiers component expects in its type field. The full catalogue of attribute IDs lives with the Attribute system; when you need a stat that isn’t one of these, the wiki’s Attribute page lists every attribute ID by name, along with the exact value range each one accepts.

Now the boots. We take diamond boots and add a movement-speed bonus that only counts while they’re on your feet:

give @s diamond_boots[attribute_modifiers=[{type:"minecraft:movement_speed",slot:"feet",id:"mypack:speed_boost",amount:0.1,operation:"add_multiplied_base"}]]

The operation:"add_multiplied_base" with amount:0.1 means “add 10% of your base walking speed,” and slot:"feet" means the bonus only applies while the boots are actually worn. Drop them in a chest and you slow back down.

The durability lifecycle

The last family of components controls an item’s durability: how much wear it can take, whether it can be enchanted, and what fixes it. You met several of these in passing already (the fence-pickaxe used max_damage and damage); here they are in full.

max_damage is an integer: the maximum damage an item can take before breaking, in other words its total durability. If it isn’t set, the item can’t take damage at all. It must be a positive non-zero integer, and it can’t be combined with a max_stack_size greater than 1 (a tool that wears out can’t stack). For example:

give @s diamond_pickaxe[max_damage=4]

This is “a diamond pickaxe that can only be used 4 times before breaking.”

damage is an integer: the number of uses already consumed, not the amount remaining. A fresh item is 0. The durability bar only appears when both damage and max_damage are present, which is why the fence example earlier set damage=0 explicitly.

give @s diamond_axe[damage=500]

This is “a diamond axe with 500 points of damage” (that is, 500 uses already spent).

unbreakable, when present, makes the item never lose durability: the durability bar disappears and a blue “Unbreakable” line is added to the tooltip. Its value is an empty object:

give @p wooden_spear[unbreakable={}]

enchantable decides whether the enchanting table works on the item. It has one field, value, a positive integer for the item’s enchantability: a higher number lets stronger enchantments be offered. For example:

give @s elytra[enchantable={value:15}]

This is “a pair of elytra that can be enchanted in an enchanting table with an enchantability of 15.” (Writing the enchantments themselves, the enchantments component and custom enchantment files, is a job for Chapters 24 and 35.)

repair_cost is an integer: the number of experience levels added to the base cost when you repair, combine, or rename the item in an anvil. A fresh item is 0; the number climbs each time you work the item, which is why heavily-used gear gets “too expensive.”

give @s diamond_sword[repair_cost=5]

repairable says what materials can repair the item in an anvil. Its one field, items, is a single item ID, a list of item IDs, or a #-prefixed item tag. For example:

give @p diamond_sword[repairable={items:"stick"}]

This is “a diamond sword that can be repaired with sticks in an anvil.”

use_cooldown sets a cooldown after the item is used (like the ender pearl’s). Its fields:

  • seconds: the cooldown length in seconds.
  • cooldown_group: an optional resource location. If set, the item shares its cooldown with every other item in the same group instead of just other items of its own type.

For example:

give @p ender_pearl[use_cooldown={seconds:10,cooldown_group:"foo:bar"}]

This is a 10-second cooldown that also applies to any item sharing the foo:bar group.

Putting the three practice items in one function

Let’s collect the three practice items into a single function you can run whenever you want them. Following the rule from Chapter 9, there’s no leading slash inside the file:

mypack/data/mypack/function/make_items.mcfunction

give @s cookie[food={nutrition:4,saturation:2,can_always_eat:true},consumable={animation:'eat',on_consume_effects:[{type:'minecraft:apply_effects',effects:[{id:'minecraft:night_vision',duration:600}]}]}]
give @s diamond_pickaxe[tool={default_mining_speed:1.0,rules:[{blocks:'minecraft:stone',speed:25,correct_for_drops:true}]}]
give @s diamond_boots[attribute_modifiers=[{type:"minecraft:movement_speed",slot:"feet",id:"mypack:speed_boost",amount:0.1,operation:"add_multiplied_base"}]]
say You received a Night Vision snack, a stone-breaker pickaxe, and speed boots!

Save it, run /reload, then run:

/function mypack:make_items

You’ll get all three items at once. Eat the cookie to see your screen brighten; mine stone with the pickaxe to feel it tear through; put the boots on to run faster, and take them off to confirm the speed bonus vanishes with them.

Figure (to be captured). a player inventory holding the three custom items, with the boots equipped and the Night Vision effect active

Practice

  1. A super-snack. Make a custom food on a different item (say apple or bread) that grants two effects at once (for example Night Vision and Speed) by putting two objects in the effects list inside one apply_effects consume effect. Make it can_always_eat:true.

  2. A faster wood pickaxe. Build a tool on a wooden_pickaxe whose rules give it a high speed on the block tag #minecraft:mineable/pickaxe (every block a pickaxe normally mines), with correct_for_drops:true. Compare how it feels against your stone-only pickaxe from the chapter.

  3. A glide hat. Recreate the glider example on a different head item, combining equippable={slot:"head"} with glider={}. Equip it and try gliding off a cliff. (Remember: glider has no fields, its value is just {}.)

  4. Real armor stats. Add a second modifier to your speed boots so they also grant a little extra max health. Put a second object in the attribute_modifiers list with its own unique id, the max-health attribute in type, slot:"feet", and operation:"add_value". (Look up the attribute ID for max health (and the maximum value it accepts) on the wiki’s Attribute page; see the note above.)

What Can Go Wrong

What Went Wrong? My food item won’t let me eat it. You probably added food but forgot consumable. The food component holds the stats, but it’s the consumable component that actually makes the item consumable on use. Add a consumable={...} (even an empty set of options works for plain eating) alongside your food, and the effects will fire.

What Went Wrong? I put attack_damage inside the weapon component and the game rejected it (or ignored it). That field doesn’t exist on weapon. The weapon component only has item_damage_per_attack and disable_blocking_for_seconds, and attack damage comes from the attribute_modifiers component. Move your damage number into an attribute_modifiers entry whose type is the attack-damage attribute.

What Went Wrong? My boots’ speed bonus shows in the tooltip but doesn’t kick in, or works in any slot. Check the slot field on the modifier. Attribute modifiers only take effect when the item is in the correct equipment slot; if you leave slot off it defaults to any equipment slot, and if you set the wrong slot the bonus simply never applies. For boots, the slot is feet.