package net.mattias.pedestals.client.gui.screens.inventory; import…
- User
package net.mattias.pedestals.client.gui.screens.inventory;
import com.mojang.blaze3d.systems.RenderSystem; import net.mattias.pedestals.Pedestals; import net.mattias.pedestals.core.Constants; import net.mattias.pedestals.core.world.inventory.PedestalMenu; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Inventory;
public class PedestalScreen extends AbstractContainerScreen { private static final ResourceLocation GUI_TEXTURE = ResourceLocation.fromNamespaceAndPath(Constants.MOD_ID, "textures/gui/pedestal/pedestal_gui.png");
public PedestalScreen(PedestalMenu pMenu, Inventory pPlayerInventory, Component pTitle) { super(pMenu, pPlayerInventory, pTitle); } @Override protected void init() { super.init(); // Gets rid of labels this.inventoryLabelY = 10000; this.titleLabelY = 10000; } @Override protected void renderBg(GuiGraphics pGuiGraphics, float pPartialTick, int pMouseX, int pMouseY) { RenderSystem.setShader(GameRenderer::getPositionTexShader); RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); RenderSystem.setShaderTexture(0, GUI_TEXTURE); int x = (width - imageWidth) / 2; int y = (height - imageHeight) / 2; pGuiGraphics.blit(GUI_TEXTURE, x, y, 0, 0, imageWidth, imageHeight); } @Override public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float delta) { renderBackground(guiGraphics, mouseX, mouseY, delta); super.render(guiGraphics, mouseX, mouseY, delta); renderTooltip(guiGraphics, mouseX, mouseY); }}
package net.mattias.pedestals.client.renderer.blockentity;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Axis;
import net.mattias.pedestals.core.world.block.entity.PedestalBlockEntity; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; import net.minecraft.client.renderer.entity.ItemRenderer; import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.LightLayer;
public class PedestalRenderer implements BlockEntityRenderer { public PedestalRenderer(BlockEntityRendererProvider.Context context) {
} @Override public void render(PedestalBlockEntity pBlockEntity, float pPartialTick, PoseStack pPoseStack, MultiBufferSource pBufferSource, int pPackedLight, int pPackedOverlay) { ItemRenderer itemRenderer = Minecraft.getInstance().getItemRenderer(); ItemStack stack = pBlockEntity.inventory.getStackInSlot(0); long time = System.currentTimeMillis(); float bobbingOffset = (float) Math.sin((time % 1000) / 1000.0 * Math.PI * 2) * 0.1f; pPoseStack.pushPose(); pPoseStack.translate(0.5f, 1.5f + bobbingOffset, 0.5f); pPoseStack.scale(0.5f, 0.5f, 0.5f); pPoseStack.mulPose(Axis.YP.rotationDegrees(pBlockEntity.getRenderingRotation())); itemRenderer.renderStatic(stack, ItemDisplayContext.FIXED, getLightLevel(pBlockEntity.getLevel(), pBlockEntity.getBlockPos()), OverlayTexture.NO_OVERLAY, pPoseStack, pBufferSource, pBlockEntity.getLevel(), 1); pPoseStack.popPose(); } private int getLightLevel(Level level, BlockPos pos) { int bLight = level.getBrightness(LightLayer.BLOCK, pos); int sLight = level.getBrightness(LightLayer.SKY, pos); return LightTexture.pack(bLight, sLight); }}
NeoForge 1.21
So my Block Entity Pedestal has a gui but when trying to open it the screen menu will close immediately you can see it for a split second
Assistant
Okay, this is a common issue when integrating GUIs with Block Entities in Forge/NeoForge. The problem is likely related to how the container (PedestalMenu) is being created and handled, and how the screen (PedestalScreen) is being opened. Here's a breakdown of potential causes and solutions, along with a focus on the code you've provided. I'll cover common pitfalls and debugging steps.
Understanding the Flow
- Player Interaction: The player right-clicks the pedestal block.
- Block Entity Interaction: The block entity's
onBlockEntityTickor similar method (or a handler registered viaBlockEntityEvents.OPEN_BLOCK_ENTITY) detects the interaction. - Container Creation: The block entity creates an instance of
PedestalMenu. This is crucial. The container needs to be associated with the block entity. - Screen Creation: The container is used to create an instance of
PedestalScreen. - Screen Display: The screen is opened to the player.
- Container Synchronization: The container handles player input and updates the block entity's inventory.
Common Causes and Solutions
-
Container Not Properly Associated with Block Entity:
- Problem: The
PedestalMenuis created without a proper reference to thePedestalBlockEntity. When the screen tries to access data from the container, it doesn't have the correct context. - Solution: Ensure your
PedestalMenuconstructor takes thePedestalBlockEntityas an argument and stores it as a member variable. This is how the container knows which pedestal it's managing.
public class PedestalMenu extends AbstractContainerMenu { // Or whatever base class you're using private final PedestalBlockEntity blockEntity; private final Inventory playerInventory; public PedestalMenu(int pContainerId, Inventory pPlayerInventory, PedestalBlockEntity pBlockEntity) { super(MenuType.PEDESTAL, pContainerId); // Replace MenuType.PEDESTAL with your registered MenuType this.blockEntity = pBlockEntity; this.playerInventory = pPlayerInventory; // Add slots to the container (pedestal slots, player inventory slots, etc.) // Example: addSlot(new Slot(blockEntity.inventory, 0, 80, 40)); // Slot for the item in the pedestal for (int i = 0; i < 9; ++i) { addSlot(new Slot(pPlayerInventory, i, 8, 18 + i * 18)); } for (int i = 0; i < 3; ++i) { for (int j = 0; j < 9; ++j) { addSlot(new Slot(pPlayerInventory, 9 + j + i * 9, 8 + j * 18, 18 + i * 18)); } } } // Methods to access the block entity's data (e.g., get the item in the pedestal) public PedestalBlockEntity getBlockEntity() { return blockEntity; } } - Problem: The
-
Incorrect Menu Type Registration:
- Problem: You haven't registered the
MenuTypefor yourPedestalMenucorrectly. This is how Minecraft knows what kind of container to create. - Solution: Register a
MenuTypein your mod initialization.
public static final MenuType<PedestalMenu> PEDESTAL_MENU_TYPE = Registry.register( Registries.MENU, new ResourceLocation(Constants.MOD_ID, "pedestal_menu").toString(), () -> PedestalMenu::new );Then, in your
PedestalMenuconstructor, use thisMenuType:public PedestalMenu(int pContainerId, Inventory pPlayerInventory, PedestalBlockEntity pBlockEntity) { super(PedestalScreen.PEDESTAL_MENU_TYPE, pContainerId); // ... } - Problem: You haven't registered the
-
Incorrect Screen Opening Logic:
- Problem: The code that opens the
PedestalScreenis flawed. It might be creating the container incorrectly or not sending the necessary packets to the client. - Solution: The typical way to open a screen is to send a
ClientboundOpenScreenPacketfrom the server to the client. This packet tells the client to display the screen. This is usually done in the block entity's interaction handler.
// In your PedestalBlockEntity (or a handler registered with BlockEntityEvents.RIGHT_CLICK_BLOCK_ENTITY) public InteractionResult onBlockEntityClick(BlockState state, Level level, BlockPos pos, Player player, Hand hand, ItemStack stack) { if (!level.isClientSide()) { // Only open on the server player.openMenu(PEDESTAL_MENU_TYPE, (buf) -> { buf.writeInt(pos.getX()); buf.writeInt(pos.getY()); buf.writeInt(pos.getZ()); }); } return InteractionResult.SUCCESS; } - Problem: The code that opens the
-
Synchronization Issues:
- Problem: The block entity's data isn't being synchronized to the client correctly. This can cause the container to display incorrect information or crash.
- Solution: Use
BlockEntityDataSaverto ensure that the block entity's data is saved and loaded correctly. Also, consider using network packets to send updates to the client if the data changes frequently.
-
Timing Issues:
- Problem: The screen is being opened before the container is fully initialized.
- Solution: Ensure that the container is created and initialized before you attempt to open the screen. This is usually handled correctly by the
ClientboundOpenScreenPacket, but it's worth checking.
Debugging Steps
- Server Logs: Check the server logs for any errors or exceptions. These can provide valuable clues about what's going wrong.
- Client Logs: Check the client logs as well.
- Debugging Statements: Add
System.out.println()statements to your code to track the flow of execution and the values of important variables. For example:- In
PedestalMenu: Print thepBlockEntityto verify that it's being passed correctly. - In
PedestalScreen: Print themenuto verify that it's a validPedestalMenu.
- In
- Network Sniffing: Use a tool like Wireshark to sniff the network traffic between the client and the server. This can help you see if the
ClientboundOpenScreenPacketis being sent correctly. - Step-by-Step Debugging: Use an IDE (like IntelliJ IDEA or Eclipse) to step through your code line by line and see what's happening.
Review Your Code
- PedestalBlockEntity: How are you handling the right-click interaction? Are you creating the
PedestalMenucorrectly? - PedestalMenu: Is the
PedestalBlockEntitybeing stored as a member variable? Are you using the correctMenuType? - PedestalScreen: Is the screen receiving a valid
PedestalMenu? - Mod Initialization: Have you registered the
MenuTypecorrectly?
Your Code Review
Your code snippets look generally correct, but the key is the association between the
PedestalBlockEntityand thePedestalMenu. Make sure you've implemented the interaction handler (e.g.,onBlockEntityClick) in your block entity and that it's sending theClientboundOpenScreenPacketwith the correct data. Also, double-check theMenuTyperegistration.Let me know if you can provide the code for:
- The interaction handler in your
PedestalBlockEntity(where you open the screen). - The registration of your
MenuType.
With that information, I can give you more specific guidance.
- User
Here is all the code for the pedestal
package net.mattias.pedestals.client.renderer.blockentity;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Axis;
import net.mattias.pedestals.core.world.block.entity.PedestalBlockEntity; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; import net.minecraft.client.renderer.entity.ItemRenderer; import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.LightLayer;
public class PedestalRenderer implements BlockEntityRenderer { public PedestalRenderer(BlockEntityRendererProvider.Context context) {
} @Override public void render(PedestalBlockEntity pBlockEntity, float pPartialTick, PoseStack pPoseStack, MultiBufferSource pBufferSource, int pPackedLight, int pPackedOverlay) { ItemRenderer itemRenderer = Minecraft.getInstance().getItemRenderer(); ItemStack stack = pBlockEntity.inventory.getStackInSlot(0); long time = System.currentTimeMillis(); float bobbingOffset = (float) Math.sin((time % 1000) / 1000.0 * Math.PI * 2) * 0.1f; pPoseStack.pushPose(); pPoseStack.translate(0.5f, 1.5f + bobbingOffset, 0.5f); pPoseStack.scale(0.5f, 0.5f, 0.5f); pPoseStack.mulPose(Axis.YP.rotationDegrees(pBlockEntity.getRenderingRotation())); itemRenderer.renderStatic(stack, ItemDisplayContext.FIXED, getLightLevel(pBlockEntity.getLevel(), pBlockEntity.getBlockPos()), OverlayTexture.NO_OVERLAY, pPoseStack, pBufferSource, pBlockEntity.getLevel(), 1); pPoseStack.popPose(); } private int getLightLevel(Level level, BlockPos pos) { int bLight = level.getBrightness(LightLayer.BLOCK, pos); int sLight = level.getBrightness(LightLayer.SKY, pos); return LightTexture.pack(bLight, sLight); }}
package net.mattias.pedestals.client;
import net.mattias.pedestals.core.Constants; import net.mattias.pedestals.core.registry.ModBlockEntities; import net.mattias.pedestals.core.registry.ModMenus; import net.mattias.pedestals.client.gui.screens.inventory.PedestalScreen; import net.mattias.pedestals.client.renderer.blockentity.PedestalRenderer; import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.fml.common.EventBusSubscriber; import net.neoforged.fml.common.EventBusSubscriber.Bus; import net.neoforged.api.distmarker.Dist; import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent; import net.neoforged.neoforge.client.event.EntityRenderersEvent;
@EventBusSubscriber( modid = Constants.MOD_ID, bus = Bus.MOD, value = Dist.CLIENT ) public class PedestalsClient {
@SubscribeEvent public static void onRegisterScreens(RegisterMenuScreensEvent event) { event.register(ModMenus.PEDESTAL.get(), PedestalScreen::new); } @SubscribeEvent public static void onRegisterRenderers(EntityRenderersEvent.RegisterRenderers event) { event.registerBlockEntityRenderer(ModBlockEntities.PEDESTAL.get(), PedestalRenderer::new); }}
package net.mattias.pedestals.client.gui.screens.inventory;
import com.mojang.blaze3d.systems.RenderSystem; import net.mattias.pedestals.Pedestals; import net.mattias.pedestals.core.Constants; import net.mattias.pedestals.core.world.inventory.PedestalMenu; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Inventory;
public class PedestalScreen extends AbstractContainerScreen { private static final ResourceLocation GUI_TEXTURE = ResourceLocation.fromNamespaceAndPath(Constants.MOD_ID, "textures/gui/pedestal/pedestal_gui.png");
public PedestalScreen(PedestalMenu pMenu, Inventory pPlayerInventory, Component pTitle) { super(pMenu, pPlayerInventory, pTitle); } @Override protected void init() { super.init(); // Gets rid of labels this.inventoryLabelY = 10000; this.titleLabelY = 10000; } @Override protected void renderBg(GuiGraphics pGuiGraphics, float pPartialTick, int pMouseX, int pMouseY) { RenderSystem.setShader(GameRenderer::getPositionTexShader); RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); RenderSystem.setShaderTexture(0, GUI_TEXTURE); int x = (width - imageWidth) / 2; int y = (height - imageHeight) / 2; pGuiGraphics.blit(GUI_TEXTURE, x, y, 0, 0, imageWidth, imageHeight); } @Override public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float delta) { renderBackground(guiGraphics, mouseX, mouseY, delta); super.render(guiGraphics, mouseX, mouseY, delta); renderTooltip(guiGraphics, mouseX, mouseY); }}
package net.mattias.pedestals.core.world.block.entity;
import net.mattias.pedestals.core.registry.ModBlockEntities; import net.mattias.pedestals.core.world.inventory.PedestalMenu; import net.minecraft.core.BlockPos; import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.game.ClientGamePacketListener; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.world.*; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.neoforged.neoforge.items.ItemStackHandler; import org.jetbrains.annotations.Nullable;
public class PedestalBlockEntity extends BlockEntity implements MenuProvider { public final ItemStackHandler inventory = new ItemStackHandler(1) { @Override protected int getStackLimit(int slot, ItemStack stack) { return 1; }
@Override protected void onContentsChanged(int slot) { setChanged(); if(!level.isClientSide()) { level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), 3); } } }; private float rotation; public PedestalBlockEntity(BlockPos pPos, BlockState pBlockState) { super(ModBlockEntities.PEDESTAL.get(), pPos, pBlockState); } public void clearContents() { inventory.setStackInSlot(0, ItemStack.EMPTY); } public void drops() { SimpleContainer inv = new SimpleContainer(inventory.getSlots()); for(int i = 0; i < inventory.getSlots(); i++) { inv.setItem(i, inventory.getStackInSlot(i)); } Containers.dropContents(this.level, this.worldPosition, inv); } @Override protected void saveAdditional(CompoundTag pTag, HolderLookup.Provider pRegistries) { super.saveAdditional(pTag, pRegistries); pTag.put("inventory", inventory.serializeNBT(pRegistries)); } @Override protected void loadAdditional(CompoundTag pTag, HolderLookup.Provider pRegistries) { super.loadAdditional(pTag, pRegistries); inventory.deserializeNBT(pRegistries, pTag.getCompound("inventory")); } public float getRenderingRotation() { rotation += 0.5f; if(rotation >= 360) { rotation = 0; } return rotation; } @Override public Component getDisplayName() { return Component.translatable( "block.pedestals.pedestal"); } @Nullable @Override public AbstractContainerMenu createMenu(int pContainerId, Inventory pPlayerInventory, Player pPlayer) { return new PedestalMenu(pContainerId, pPlayerInventory, this); } @Nullable @Override public Packet<ClientGamePacketListener> getUpdatePacket() { return ClientboundBlockEntityDataPacket.create(this); } @Override public CompoundTag getUpdateTag(HolderLookup.Provider pRegistries) { return saveWithoutMetadata(pRegistries); }}
package net.mattias.pedestals.core.world.block;
import com.mojang.serialization.MapCodec; import net.mattias.pedestals.core.world.block.entity.PedestalBlockEntity; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.Containers; import net.minecraft.world.InteractionHand; import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.SimpleMenuProvider; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.Nullable;
public class PedestalBlock extends BaseEntityBlock { public static final VoxelShape SHAPE = Block.box(2, 0, 2, 14, 13, 14); public static final MapCodec CODEC = simpleCodec(PedestalBlock::new);
public PedestalBlock(Properties properties) { super(properties); } @Override protected MapCodec<? extends BaseEntityBlock> codec() { return CODEC; } @Override protected VoxelShape getShape(BlockState pState, BlockGetter pLevel, BlockPos pPos, CollisionContext pContext) { return SHAPE; } @Nullable @Override public BlockEntity newBlockEntity(BlockPos pPos, BlockState pState) { return new PedestalBlockEntity(pPos, pState); } @Override protected RenderShape getRenderShape(BlockState pState) { return RenderShape.MODEL; } @Override protected void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pMovedByPiston) { if(pState.getBlock() != pNewState.getBlock()) { if(pLevel.getBlockEntity(pPos) instanceof PedestalBlockEntity pedestalBlockEntity) { pedestalBlockEntity.drops(); pLevel.updateNeighbourForOutputSignal(pPos, this); } } super.onRemove(pState, pLevel, pPos, pNewState, pMovedByPiston); } @Override protected ItemInteractionResult useItemOn(ItemStack pStack, BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand, BlockHitResult pHitResult) { if(pLevel.getBlockEntity(pPos) instanceof PedestalBlockEntity pedestalBlockEntity) { if(pPlayer.isCrouching() && !pLevel.isClientSide()) { ((ServerPlayer) pPlayer).openMenu(new SimpleMenuProvider(pedestalBlockEntity, Component.literal("Pedestal")), pPos); return ItemInteractionResult.SUCCESS; } if(pedestalBlockEntity.inventory.getStackInSlot(0).isEmpty() && !pStack.isEmpty()) { pedestalBlockEntity.inventory.insertItem(0, pStack.copy(), false); pStack.shrink(1); pLevel.playSound(pPlayer, pPos, SoundEvents.ITEM_PICKUP, SoundSource.BLOCKS, 1f, 2f); } else if(pStack.isEmpty()) { ItemStack stackOnPedestal = pedestalBlockEntity.inventory.extractItem(0, 1, false); pPlayer.setItemInHand(InteractionHand.MAIN_HAND, stackOnPedestal); pedestalBlockEntity.clearContents(); pLevel.playSound(pPlayer, pPos, SoundEvents.ITEM_PICKUP, SoundSource.BLOCKS, 1f, 1f); } } return ItemInteractionResult.SUCCESS; }}
package net.mattias.pedestals.core.world.inventory;
import net.mattias.pedestals.core.registry.ModBlocks; import net.mattias.pedestals.core.registry.ModMenus; import net.mattias.pedestals.core.world.block.entity.PedestalBlockEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ContainerLevelAccess; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.neoforged.neoforge.items.SlotItemHandler;
public class PedestalMenu extends AbstractContainerMenu { public final PedestalBlockEntity blockEntity; private final Level level;
public PedestalMenu(int pContainerId, Inventory inv, FriendlyByteBuf extraData) { this(pContainerId, inv, inv.player.level().getBlockEntity(extraData.readBlockPos())); } public PedestalMenu(int pContainerId, Inventory inv, BlockEntity blockEntity) { super(ModMenus.PEDESTAL.get(), pContainerId); this.blockEntity = ((PedestalBlockEntity) blockEntity); this.level = inv.player.level(); addPlayerInventory(inv); addPlayerHotbar(inv); this.addSlot(new SlotItemHandler(this.blockEntity.inventory, 0, 80, 35)); } // CREDIT GOES TO: diesieben07 | https://github.com/diesieben07/SevenCommons // must assign a slot number to each of the slots used by the GUI. // For this container, we can see both the tile inventory's slots as well as the player inventory slots and the hotbar. // Each time we add a Slot to the container, it automatically increases the slotIndex, which means // 0 - 8 = hotbar slots (which will map to the InventoryPlayer slot numbers 0 - 8) // 9 - 35 = player inventory slots (which map to the InventoryPlayer slot numbers 9 - 35) // 36 - 44 = TileInventory slots, which map to our TileEntity slot numbers 0 - 8) private static final int HOTBAR_SLOT_COUNT = 9; private static final int PLAYER_INVENTORY_ROW_COUNT = 3; private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9; private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT; private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT; private static final int VANILLA_FIRST_SLOT_INDEX = 0; private static final int TE_INVENTORY_FIRST_SLOT_INDEX = VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT; // THIS YOU HAVE TO DEFINE! private static final int TE_INVENTORY_SLOT_COUNT = 1; // must be the number of slots you have! @Override public ItemStack quickMoveStack(Player playerIn, int pIndex) { Slot sourceSlot = slots.get(pIndex); if (sourceSlot == null || !sourceSlot.hasItem()) return ItemStack.EMPTY; //EMPTY_ITEM ItemStack sourceStack = sourceSlot.getItem(); ItemStack copyOfSourceStack = sourceStack.copy(); // Check if the slot clicked is one of the vanilla container slots if (pIndex < VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT) { // This is a vanilla container slot so merge the stack into the tile inventory if (!moveItemStackTo(sourceStack, TE_INVENTORY_FIRST_SLOT_INDEX, TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT, false)) { return ItemStack.EMPTY; // EMPTY_ITEM } } else if (pIndex < TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT) { // This is a TE slot so merge the stack into the players inventory if (!moveItemStackTo(sourceStack, VANILLA_FIRST_SLOT_INDEX, VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT, false)) { return ItemStack.EMPTY; } } else { System.out.println("Invalid slotIndex:" + pIndex); return ItemStack.EMPTY; } // If stack size == 0 (the entire stack was moved) set slot contents to null if (sourceStack.getCount() == 0) { sourceSlot.set(ItemStack.EMPTY); } else { sourceSlot.setChanged(); } sourceSlot.onTake(playerIn, sourceStack); return copyOfSourceStack; } @Override public boolean stillValid(Player pPlayer) { return stillValid(ContainerLevelAccess.create(level, blockEntity.getBlockPos()), pPlayer, ModBlocks.PEDESTAL.get()); } private void addPlayerInventory(Inventory playerInventory) { for (int i = 0; i < 3; ++i) { for (int l = 0; l < 9; ++l) { this.addSlot(new Slot(playerInventory, l + i * 9 + 9, 8 + l * 18, 84 + i * 18)); } } } private void addPlayerHotbar(Inventory playerInventory) { for (int i = 0; i < 9; ++i) { this.addSlot(new Slot(playerInventory, i, 8 + i * 18, 142)); } }}
Assistant
Okay, this is a good set of code. I've identified the likely culprit and a few supporting issues.
The Core Problem: Incorrect Container Creation in the Block Entity Interaction
The issue is in your
PedestalBlock'suseItemOnmethod. You're usingSimpleMenuProviderto open the screen, but this doesn't create the correctPedestalMenuwith the block entity association.SimpleMenuProvideris meant for very simple cases, not for containers that need to interact with a block entity's data.Solution:
You need to create and open the
PedestalMenudirectly from the block entity's interaction handler. This is the same logic you're using in the server-side container creation in thePedestalMenuconstructor that takes aBlockEntity.// In PedestalBlock.java, inside useItemOn() if(pLevel.getBlockEntity(pPos) instanceof PedestalBlockEntity pedestalBlockEntity) { if(pPlayer.isCrouching() && !pLevel.isClientSide()) { pPlayer.openMenu(new PedestalMenu(pContainerId, pPlayer.getInventory(), pedestalBlockEntity)); // Correct way to open return ItemInteractionResult.SUCCESS; } // ... (rest of your interaction logic) }Explanation:
pPlayer.openMenu()expects aMenuinstance (in this case, yourPedestalMenu).- We create a new
PedestalMenuinstance, passing in:pContainerId: A unique ID for the container. This is automatically generated by Minecraft.pPlayer.getInventory(): The player's inventory.pedestalBlockEntity: Crucially, the block entity instance. This is what links the container to the pedestal.
Supporting Issues and Recommendations
-
Missing
pContainerIdinPedestalMenuConstructor:Your
PedestalMenuhas two constructors. The one taking aFriendlyByteBufis used when the container is recreated on the client side after receiving theClientboundOpenScreenPacket. However, the constructor you're calling fromPedestalBlockdoesn't take aFriendlyByteBuf. You need to add a constructor that takes thepContainerId,Inventory, andBlockEntity. I've added this to the corrected code above. -
FriendlyByteBufConstructor:Keep the
FriendlyByteBufconstructor inPedestalMenuas it's needed for client-side container recreation. -
Slot Indexing in
PedestalMenu:Your slot indexing logic in
PedestalMenu(the comments aboutTE_INVENTORY_FIRST_SLOT_INDEX, etc.) looks correct and well-documented. This is good. -
stillValidMethod:Your
stillValidmethod is correct. -
getUpdatePacketandgetUpdateTag:These methods are correctly implemented for data synchronization.
Revised Code Snippets (Key Changes)
-
PedestalBlock.java (useItemOn):
if(pLevel.getBlockEntity(pPos) instanceof PedestalBlockEntity pedestalBlockEntity) { if(pPlayer.isCrouching() && !pLevel.isClientSide()) { pPlayer.openMenu(new PedestalMenu(pContainerId, pPlayer.getInventory(), pedestalBlockEntity)); return ItemInteractionResult.SUCCESS; } // ... (rest of your interaction logic) } -
PedestalMenu.java (Add Constructor):
public PedestalMenu(int pContainerId, Inventory inv, PedestalBlockEntity blockEntity) { super(ModMenus.PEDESTAL.get(), pContainerId); this.blockEntity = blockEntity; this.level = inv.player.level(); addPlayerInventory(inv); addPlayerHotbar(inv); this.addSlot(new SlotItemHandler(this.blockEntity.inventory, 0, 80, 35)); }
Debugging Steps (After Applying Changes)
- Clean and Rebuild: Do a clean build of your project to ensure that all changes are compiled correctly.
- Server Logs: Check the server logs for any errors when you right-click the pedestal.
- Client Logs: Check the client logs for any errors related to opening the screen.
- Network Sniffing (If Necessary): If you're still having trouble, use a network sniffer to verify that the
ClientboundOpenScreenPacketis being sent correctly.
Important: After making these changes, test thoroughly. Make sure you can open the GUI, interact with the pedestal's inventory, and that the changes are synchronized correctly between the client and the server.
Let me know if you have any further questions or if you're still encountering issues after applying these changes. I'm here to help!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.