Jump to content

Recommended Posts

Posted

Ok, so I've been working on a gui and I've gotten most of it to work but just as I am finishing an error appeared,

Whenever I right click the block instead of showing the gui minecraft crashes.

this is the error message: 

  Quote

java.lang.NullPointerException: Ticking entity
    at java.util.Objects.requireNonNull(Objects.java:208) ~[?:?] {}
    at net.minecraft.world.inventory.AbstractContainerMenu.broadcastChanges(AbstractContainerMenu.java:169) ~[forge-1.19-41.0.107_mapped_official_1.19-recomp.jar%23181!/:?] {re:classloading}
    at net.minecraft.server.level.ServerPlayer.tick(ServerPlayer.java:414) ~[forge-1.19-41.0.107_mapped_official_1.19-recomp.jar%23181!/:?] {re:classloading,pl:accesstransformer:B}
    at net.minecraft.server.level.ServerLevel.tickNonPassenger(ServerLevel.java:657) ~[forge-1.19-41.0.107_mapped_official_1.19-recomp.jar%23181!/:?] {re:classloading,pl:accesstransformer:B}
    at net.minecraft.world.level.Level.guardEntityTick(Level.java:457) ~[forge-1.19-41.0.107_mapped_official_1.19-recomp.jar%23181!/:?] {re:classloading,pl:accesstransformer:B}
    at net.minecraft.server.level.ServerLevel.lambda$tick$3(ServerLevel.java:322) ~[forge-1.19-41.0.107_mapped_official_1.19-recomp.jar%23181!/:?] {re:classloading,pl:accesstransformer:B}
    at net.minecraft.world.level.entity.EntityTickList.forEach(EntityTickList.java:53) ~[forge-1.19-41.0.107_mapped_official_1.19-recomp.jar%23181!/:?] {re:classloading}
    at net.minecraft.server.level.ServerLevel.tick(ServerLevel.java:302) ~[forge-1.19-41.0.107_mapped_official_1.19-recomp.jar%23181!/:?] {re:classloading,pl:accesstransformer:B}
    at net.minecraft.server.MinecraftServer.tickChildren(MinecraftServer.java:866) ~[forge-1.19-41.0.107_mapped_official_1.19-recomp.jar%23181!/:?] {re:classloading,pl:accesstransformer:B}
    at net.minecraft.server.MinecraftServer.tickServer(MinecraftServer.java:806) ~[forge-1.19-41.0.107_mapped_official_1.19-recomp.jar%23181!/:?] {re:classloading,pl:accesstransformer:B}
    at net.minecraft.client.server.IntegratedServer.tickServer(IntegratedServer.java:84) ~[forge-1.19-41.0.107_mapped_official_1.19-recomp.jar%23181!/:?] {re:classloading,pl:runtimedistcleaner:A}
    at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:654) ~[forge-1.19-41.0.107_mapped_official_1.19-recomp.jar%23181!/:?] {re:classloading,pl:accesstransformer:B}
    at net.minecraft.server.MinecraftServer.lambda$spin$2(MinecraftServer.java:245) ~[forge-1.19-41.0.107_mapped_official_1.19-recomp.jar%23181!/:?] {re:classloading,pl:accesstransformer:B}
    at java.lang.Thread.run(Thread.java:833) ~[?:?] {}
 

Expand  

and this is my code:

ExampleChestScreen.java:

public class ExampleChestScreen extends AbstractContainerScreen<ExampleChestContainer> {
    private static final ResourceLocation TEXTURE = new ResourceLocation(KnoxiItems.MOD_ID,
            "textures/gui/magical_workbench_gui.png");

    private ExtendedButton beanButton;

    public ExampleChestScreen(ExampleChestContainer container, Inventory playerInv, Component title) {
        super(container, playerInv, title);
        this.leftPos = 0;
        this.topPos = 0;
    }

    @Override
    public void render(PoseStack stack, int mouseX, int mouseY, float partialTicks) {
        super.render(stack, mouseX, mouseY, partialTicks);
        this.font.draw(stack, this.title, this.leftPos + 20, this.topPos + 5, 0x404040);
        this.font.draw(stack, this.playerInventoryTitle, this.leftPos + 8, this.topPos + 75, 0x404040);
    }

    @Override
    protected void init() {
        super.init();
        this.beanButton = addRenderableWidget(
                new ExtendedButton(this.leftPos, this.topPos, 16, 16, Component.literal("beans"),
                        btn -> Minecraft.getInstance().player.displayClientMessage(Component.literal("beans"), false)));
    }

    @Override
    protected void renderBg(PoseStack stack, float mouseX, int mouseY, int partialTicks) {
        renderBackground(stack);
        RenderSystem.setShader(GameRenderer::getPositionTexShader);
        RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
        RenderSystem.setShaderTexture(0, TEXTURE);
        blit(stack, this.leftPos, this.topPos, 0, 0, this.imageWidth, this.imageHeight);
    }

    @Override
    protected void renderLabels(PoseStack stack, int mouseX, int mouseY) {
    }
}

ExampleChestBlockEntity.java:

public class ExampleChestBlockEntity extends BlockEntity {
    public static Component TITLE = Component.literal("Example Chest");
    IItemHandler inventory;
    public ExampleChestBlockEntity(BlockPos pos, BlockState state) {
        super(ModBlockEntities.EXAMPLE_CHEST.get(), pos, state);
        inventory = new IItemHandler() {
            private ItemStack[] Inventory = new ItemStack[27];
            @Override
            public int getSlots() {
                return Inventory.length;
            }

            @Override
            public @NotNull ItemStack getStackInSlot(int slot) {
                return Inventory[slot];
            }

            @Override
            public @NotNull ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate) {
                Inventory[slot] = stack;
                return Inventory[slot];
            }

            @Override
            public @NotNull ItemStack extractItem(int slot, int amount, boolean simulate) {
                if (!(amount >= Inventory[slot].getCount())) {
                    Inventory[slot] = new ItemStack(Inventory[slot].getItem(), Inventory[slot].getCount() - amount);
                } else {
                    Inventory[slot] = null;
                }
                return Inventory[slot];
            }

            @Override
            public int getSlotLimit(int slot) {
                return 64;
            }

            @Override
            public boolean isItemValid(int slot, @NotNull ItemStack stack) {
                return true;
            }
        };
    }
}

ExampleChestContainer.java:

public class ExampleChestContainer extends AbstractContainerMenu {
    private final ContainerLevelAccess containerAccess;

    // Client Constructor
    public ExampleChestContainer(int id, Inventory playerInv) {
        this(id, playerInv, new ItemStackHandler(27), BlockPos.ZERO);
    }

    // Server constructor
    public ExampleChestContainer(int id, Inventory playerInv, IItemHandler slots, BlockPos pos) {
        super(ModBlockContainers.EXAMPLE_CHEST.get(), id);
        this.containerAccess = ContainerLevelAccess.create(playerInv.player.level, pos);

        final int slotSizePlus2 = 18, startX = 8, startY = 86, hotbarY = 144, inventoryY = 18;

        for (int row = 0; row < 3; row++) {
            for (int column = 0; column < 9; column++) {
                addSlot(new SlotItemHandler(slots, row * 9 + column, startX + column * slotSizePlus2,
                        inventoryY + row * slotSizePlus2));
            }
        }

        for (int row = 0; row < 3; row++) {
            for (int column = 0; column < 9; column++) {
                addSlot(new Slot(playerInv, 9 + row * 9 + column, startX + column * slotSizePlus2,
                        startY + row * slotSizePlus2));
            }
        }

        for (int column = 0; column < 9; column++) {
            addSlot(new Slot(playerInv, column, startX + column * slotSizePlus2, hotbarY));
        }
    }

    @Override
    public ItemStack quickMoveStack(Player player, int index) {
        var retStack = ItemStack.EMPTY;
        final Slot slot = getSlot(index);
        if (slot.hasItem()) {
            final ItemStack item = slot.getItem();
            retStack = item.copy();
            if (index < 27) {
                if (!moveItemStackTo(item, 27, this.slots.size(), true))
                    return ItemStack.EMPTY;
            } else if (!moveItemStackTo(item, 0, 27, false))
                return ItemStack.EMPTY;

            if (item.isEmpty()) {
                slot.set(ItemStack.EMPTY);
            } else {
                slot.setChanged();
            }
        }

        return retStack;
    }

    @Override
    public boolean stillValid(Player player) {
        return stillValid(this.containerAccess, player, ModBlocks.EXAMPLE_CHEST.get());
    }

    public static MenuConstructor getServerContainer(ExampleChestBlockEntity chest, BlockPos pos) {
        return (id, playerInv, player) -> new ExampleChestContainer(id, playerInv, chest.inventory, pos);
    }
}

ExampleChestBlock.java:

public class ExampleChestBlock extends HorizontalDirectionalBlock implements EntityBlock {
    public ExampleChestBlock(Properties properties) {
        super(properties);
        registerDefaultState(defaultBlockState().setValue(FACING, Direction.NORTH));
    }

    @Override
    public BlockState getStateForPlacement(BlockPlaceContext context) {
        return defaultBlockState().setValue(FACING, context.getHorizontalDirection().getOpposite());
    }

   /* @Override
    public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState state,
                                                                  BlockEntityType<T> beType) {
        //return level.isClientSide ? null
        //        : (level0, pos, state0, blockEntity) -> ((ExampleChestBlockEntity) blockEntity).tick();
        return super.defaultBlockState().getTicker(level, beType);
    }*/

    @Nullable
    @Override
    public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level p_153212_, BlockState p_153213_, BlockEntityType<T> p_153214_) {
        return EntityBlock.super.getTicker(p_153212_, p_153213_, p_153214_);
    }

    @Override
    public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
        return new ExampleChestBlockEntity(pos, state);
    }

    @Override
    public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand,
                                 BlockHitResult result) {
        if (!level.isClientSide && level.getBlockEntity(pos) instanceof final ExampleChestBlockEntity chest) {
            final MenuProvider container = new SimpleMenuProvider(ExampleChestContainer.getServerContainer(chest, pos),
                    ExampleChestBlockEntity.TITLE);
            NetworkHooks.openScreen((ServerPlayer) player, container, pos);
        }

        return InteractionResult.SUCCESS;
    }

    @Override
    protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
        super.createBlockStateDefinition(builder);
        builder.add(FACING);
    }
}

Thank you in advance for any help

Posted

Look at the code where it crashes. It has an itemStack::copy of the item stack in each slot.

The error says one of your slots contains a null, when you should be using ItemStack.EMPTY for unoccupied slots.

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

Posted

The vanilla chest uses 

  Quote

   private NonNullList<ItemStack> items = NonNullList.withSize(27, ItemStack.EMPTY);
 

Expand  

For its items.

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

Posted

Thanks but now it says this when i right click it:

  Quote

[07:34:18] [Render thread/WARN] [minecraft/MenuScreens]: Failed to create screen for menu type: knoxiitems:example_chest

Expand  

 

Posted

You need to register a Screen for your Menu in FMLClientSetupEvent in #enqueueWork via MenuScreens#register.
If you already register a Screen for your Menu, please post the code you are using for it.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • just rewatched the tutorial and my code is exactly the same as kaupenjoe's.  the item is added into the game but like i said to start it doesnt have a texture or a proper name for whatever reason.
    • yes the name is en_us.json and it is in resources -> assests -> testmod -> lang folders.  i have checked my code and am pretty confident that the code itself is correct.  i even tried loading the project in eclipse and it has the same problems, I think i will just rewatch the whole tutorial and will give an update on the situation.
    • same error, I also tried removing Valkyrian skies as well because I noticed it coming up a lot in the debug log errors
    • Hey man,    i have only been modding Minecraft for a few days but maybe I can help you. First of all make sure to follow every step of Kaupenjoe's tutorial, I found it to been very helpful and complete. The game uses the raw translation key for the item (in your case "item.testmod.alexandrite") if it can't find the correct lang file. Make sure it's name is "en_us.json" and it is saved under "ressources" -> "assets" -> "testmod".
    • whenever I try to get this item to render into the game it appears with the not texture purple and black squares and calls itself by the lang translation file path instead of the name i gave it.   { "item.testmod.alexandrite": "Alexandrite" } this is the lang json file package net.Hurst.testmod.item; import net.Hurst.testmod.TestMod; import net.minecraft.world.item.Item; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; public class ModItems { public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, TestMod.MOD_ID); public static final RegistryObject<Item> ALEXANDRITE = ITEMS.register("alexandrite", () -> new Item(new Item.Properties())); public static void register(IEventBus eventBus){ ITEMS.register(eventBus); } } this is my ModItems.java file package net.Hurst.testmod; import com.mojang.logging.LogUtils; import net.Hurst.testmod.item.ModItems; import net.minecraft.world.item.CreativeModeTabs; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.BuildCreativeModeTabContentsEvent; import net.minecraftforge.event.server.ServerStartingEvent; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.slf4j.Logger; // The value here should match an entry in the META-INF/mods.toml file @Mod(TestMod.MOD_ID) public class TestMod { public static final String MOD_ID = "testmod"; private static final Logger LOGGER = LogUtils.getLogger(); public TestMod() { IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); modEventBus.addListener(this::commonSetup); ModItems.register(modEventBus); MinecraftForge.EVENT_BUS.register(this); modEventBus.addListener(this::addCreative); ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.SPEC); } private void commonSetup(final FMLCommonSetupEvent event) { } // Add the example block item to the building blocks tab private void addCreative(BuildCreativeModeTabContentsEvent event) { if(event.getTabKey() == CreativeModeTabs.INGREDIENTS){ event.accept(ModItems.ALEXANDRITE); } } // You can use SubscribeEvent and let the Event Bus discover methods to call @SubscribeEvent public void onServerStarting(ServerStartingEvent event) { } // You can use EventBusSubscriber to automatically register all static methods in the class annotated with @SubscribeEvent @Mod.EventBusSubscriber(modid = MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) public static class ClientModEvents { @SubscribeEvent public static void onClientSetup(FMLClientSetupEvent event) { } } } this is my TestMod.java file { "parent": "minecraft:item/generated", "textures": { "layer0": "testmod:item/generated" } } this is my model file for the item. I am using intellij 2025.1.2 with fdk 1.21 and java 21 I would appreciate the help.
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.