Consumables
Consumables are items which can be used over a period of time, 'consuming' them in the process. Anything that can be eaten or drunk in Minecraft is a consumable of some kind.
The Consumable Data Component
Any item that can be consumed has the DataComponents#CONSUMABLE component. The backing record Consumable defines how the item is consumed and what effects to apply after consumption.
A Consumable can be created either by directly calling the record constructor or via Consumable#builder, which sets the defaults for each field, followed by build once finished:
consumeSeconds- Afloatrepresenting the number of seconds needed to fully consume the item.Item#finishUsingItemis called after the alloted time passes. Defaults to 1.6 seconds, or 32 ticks.animation- Sets theItemUseAnimationto play while the item is being used. Defaults toItemUseAnimation#EAT.sound- Sets theSoundEventto play while consuming the item. This must be aHolderinstance. Defaults toSoundEvents#GENERIC_EAT.- If a vanilla instance is not a
Holder<SoundEvent>, aHolderwrapped version can be obtained by callingBuiltInRegistries.SOUND_EVENT.wrapAsHolder(soundEvent).
- If a vanilla instance is not a
soundAfterConsume- Sets theSoundEventto player once the item has finished being consumed. This delegates to thePlaySoundConsumeEffect.hasConsumeParticles- Whentrue, spawns item particles every four ticks and once the item is fully consumed. Defauts totrue.onConsume- Adds aConsumeEffectto apply once the item has fully been consumed viaItem#finishUsingItem.
Vanilla provides some consumables within their Consumables class, such as #defaultFood for food items and #defaultDrink for potions and milk buckets.
The Consumable component can be added by calling Item.Properties#component:
// Assume there is some DeferredRegister.Items ITEMS
public static final DeferredItem<Item> CONSUMABLE = ITEMS.registerSimpleItem(
"consumable",
props -> props.component(
DataComponents.CONSUMABLE,
Consumable.builder()
// Spend 2 seconds, or 40 ticks, to consume
.consumeSeconds(2f)
// Sets the animation to play while consuming
.animation(ItemUseAnimation.BLOCK)
// Play sound while consuming every tick
.sound(SoundEvents.ARMOR_EQUIP_CHAIN)
// Play sound once finished consuming
.soundAfterConsume(SoundEvents.BREEZE_WIND_CHARGE_BURST)
// Don't show particles while eating
.hasConsumeParticles(false)
.onConsume(
// When finished consuming, applies the effects with a 30% chance
new ApplyStatusEffectsConsumeEffect(new MobEffectInstance(MobEffects.HUNGER, 600, 0), 0.3F)
)
// Can have multiple
.onConsume(
// Teleports the entity randomly in a 50 block radius
new TeleportRandomlyConsumeEffect(100f)
)
.build()
)
);