Back to Snippets

Custom Block Snippet.

A full custom block setup for Fabric mods using the Minecraft Java API. Covers the block class with an on-use action, block registration, block item registration, and the lang entry. Swap yourmod with your mod ID throughout.

How to Use?
Create the block class, register the block and its block item in ModBlocks, call registerModBlocks() from your mod initializer, and add the lang key to your en_us.json.

Requirements
Fabric API, Minecraft 1.20+, Java 17+.

package com.yourmod.block;

import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.ActionResult;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

public class ExampleBlock extends Block {

    public ExampleBlock(Settings settings) {
        super(settings);
    }

    // Right-click / use action on the block
    @Override
    public ActionResult onUse(
            BlockState state, World world,
            BlockPos pos, PlayerEntity player,
            BlockHitResult hit) {

        if (!world.isClient) {
            // Your custom logic here
            player.sendMessage(
                Text.literal("You clicked Example Block at " + pos.toShortString()), true
            );
        }

        return ActionResult.SUCCESS;
    }
}