October 22, 2024
Chicago 12, Melborne City, USA
java

Level.setBlock() places invisible blocks


I’m trying to create an item that places blocks that are in another hand above the block on which the item is used, but it only places the first block normally, and the others are invisible, which become normal if you right-click on them or rejoin the world

How can this be fixed?

package "my package";

import net.minecraft.core.BlockPos;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;

public class BlockPlacerItem extends Item {
    public BlockPlacerItem(Properties pProperties) {
        super(pProperties.stacksTo(1).durability(100));
    }

    @Override
    public @NotNull InteractionResult useOn(UseOnContext pContext) {
        if(!pContext.getLevel().isClientSide()) {
            Level level = pContext.getLevel();
            BlockPos position = pContext.getClickedPos();
            Player player = pContext.getPlayer();
            assert player != null;
            ItemStack item = player.getItemBySlot(EquipmentSlot.OFFHAND);
            int count = item.getCount();
            Block blockType = Block.byItem(item.getItem());

            if(blockType != Blocks.AIR) {
                for (int i = 1; i < count + 1; i++) {
                    BlockPos newPos = position.above(i);
                    level.setBlock(newPos, blockType.defaultBlockState(), 1);
                    level.setBlock(newPos, blockType.defaultBlockState(), 1);
                }
                if(!player.isCreative() && !player.isSpectator()) {
                    item.setCount(0);
                    pContext.getItemInHand().hurtAndBreak(1, Objects.requireNonNull(pContext.getPlayer()), pl -> pl.broadcastBreakEvent(pl.getUsedItemHand()));
                }
            }
        }

        return InteractionResult.SUCCESS;
    }
}



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video