Jump to content

[1.14.4][SOLVED] add item to empty inventory


andGarrett

Recommended Posts

I'm trying to add an item to an empty inventory, but what I've tried hasn't worked. I tried:

this.container.getInventory().set(0, item);

and

this.container.getInventory().set(0, item).setCount(1);

"item" in this context is an item stack containing 1 coal. I'm able to change the count if there is already an item in the container, so I know I'm accessing the correct container.

 

[SOLUTION]

use your handler's "insertItem" method.

Edited by andGarrett
found solution
Link to comment
Share on other sites

5 minutes ago, andGarrett said:

I'm trying to add an item to an empty inventory, but what I've tried hasn't worked. I tried:

this.container.getInventory().set(0, item);

and

this.container.getInventory().set(0, item).setCount(1);

"item" in this context is an item stack containing 1 coal. I'm able to change the count if there is already an item in the container, so I know I'm accessing the correct container.

Post all of your code.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Link to comment
Share on other sites

2 hours ago, Animefan8888 said:

Post all of your code.

The class is incomplete. I'm in the process of setting up the mineBlock method. currently it only really does something if the AutoMiner block is facing up and has a block above it. the important part is on line 123 in the mineBlock method.

 

package com.Garrett.backtobasics.blocks;

import net.minecraft.block.Block;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.ITickableTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemStackHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import static net.minecraft.util.Direction.*;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.util.List;

import static com.Garrett.backtobasics.blocks.ModBlocks.AUTO_MINER_TILE_ENTITY;

public class AutoMinerTileEntity extends TileEntity implements ITickableTileEntity, INamedContainerProvider {

    private static final Logger LOGGER = LogManager.getLogger();
    private LazyOptional<IItemHandler> handler = LazyOptional.of(this::createHandler);
    private int tickCounter = 0;
    private AutoMinerContainer container;

    public AutoMinerTileEntity() {

        super(AUTO_MINER_TILE_ENTITY);

    }


    // 20 ticks per second
    @Override
    public void tick() {

        tickCounter++;

        if (tickCounter >= 60) {
            tickCounter = 0;

            mineBlock();
        }
    }

    // the lazy handler postpones execution of code until it is needed for the first time and cashes it
    // so it won't be recreated every time it is used.
    private ItemStackHandler createHandler () {
        return new ItemStackHandler(1);
    }

    // reads inventory from world file on load
    @Override
    public void read(CompoundNBT tag) {
        CompoundNBT invTag = tag.getCompound("inv");
        handler.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(invTag));
        createHandler().deserializeNBT(invTag);
        super.read(tag);
    }

    // writes inventory to world file whenever world is saved
    @Override
    public CompoundNBT write(CompoundNBT tag) {
        handler.ifPresent(h -> {
            CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT();
            tag.put("inv", compound);
        });
        return super.write(tag);
    }


    // Capabilities add funcionality to blocks and items.
    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
            return handler.cast();
        }
        return super.getCapability(cap, side);
    }

    @Override
    public ITextComponent getDisplayName() {
        return new StringTextComponent(getType().getRegistryName().getPath());
    }

    @Nullable
    @Override
    public Container createMenu(int i, PlayerInventory playerInventory, PlayerEntity playerEntity) {
        this.container = new AutoMinerContainer(i, world, pos, playerInventory, playerEntity);
        return container;
    }

    private void mineBlock() {

        if (getBlockState().getValues().containsValue(UP)
                && !world.getBlockState(getPos().up()).getMaterial().isToolNotRequired()
                && world.getServer() != null
                && this.container != null) {
            if (this.container.getInventory().get(0).getCount() < this.container.getInventory().get(0).getItem().getMaxStackSize()) {
                Block block = world.getBlockState(getPos().up()).getBlock();
                ServerWorld serverWorld = world.getServer().getWorld(world.dimension.getType());
                List<ItemStack> drops = Block.getDrops(block.getDefaultState(), serverWorld, getPos().up(), super.getTileEntity());
                for (ItemStack item: drops) {
                    if (item.getItem() == this.container.getInventory().get(0).getItem()) {
                        this.container.getInventory().get(0).grow(1);
                    } else if (this.container.getInventory().get(0).isEmpty()) {
                        LOGGER.info(item);
                        this.container.getInventory().set(0, item).setCount(1); // Here's where I want to add items to the inventory
                    }

                    //LOGGER.info(drops.get(0).getItem().getRegistryName());
                    //LOGGER.info(drops.get(0).getCount());
                }
            }

        } else if (getBlockState().getValues().containsValue(DOWN)) {
            if (!world.getBlockState(getPos().down()).getMaterial().isToolNotRequired()) {
                LOGGER.info(world.getBlockState(getPos().down()).getBlock().getLootTable().toString());
            }
        } else if (getBlockState().getValues().containsValue(NORTH)) {
            if (!world.getBlockState(getPos().north()).getMaterial().isToolNotRequired()) {
                LOGGER.info(world.getBlockState(getPos().north()).getBlock().getLootTable().toString());
            }
        } else if (getBlockState().getValues().containsValue(SOUTH)) {
            if (!world.getBlockState(getPos().south()).getMaterial().isToolNotRequired()) {
                LOGGER.info(world.getBlockState(getPos().south()).getBlock().getLootTable().toString());
            }
        } else if (getBlockState().getValues().containsValue(EAST)) {
            if (!world.getBlockState(getPos().east()).getMaterial().isToolNotRequired()) {
                LOGGER.info(world.getBlockState(getPos().east()).getBlock().getLootTable().toString());
            }
        } else if (getBlockState().getValues().containsValue(WEST)) {
            if (!world.getBlockState(getPos().west()).getMaterial().isToolNotRequired()) {
                LOGGER.info(world.getBlockState(getPos().west()).getBlock().getLootTable().toString());
            }
        }
    }
}

 

Link to comment
Share on other sites

3 hours ago, andGarrett said:

this.container

Why is this a thing? What if two players open the TE at the same time....

3 hours ago, andGarrett said:

(this.container.getInventory().get(0).getCount()

Why not just use the IItemHandler you have directly?...

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Link to comment
Share on other sites

17 minutes ago, Animefan8888 said:

Why is this a thing? What if two players open the TE at the same time....

 

Why not just use the IItemHandler you have directly?...

I stored the container in an instance field because I couldn't figure out how to get access to it any other way. for your second question, I don't know how to interact with IItemHandler. I don't know if this is relevant, but the container is a different class. I figured working with the container associated with the block was the best way to effect the inventory.

Link to comment
Share on other sites

13 minutes ago, andGarrett said:

for your second question, I don't know how to interact with IItemHandler

Look at the methods inside it there are two I can think of insertItem and extractItem. 

 

16 minutes ago, andGarrett said:

I figured working with the container associated with the block was the best way to effect the inventory.

It isn't. The contents are synced from the IItemHandler when they change if you call detectAndSendChanges(I believe that is what it is called).

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Link to comment
Share on other sites

18 hours ago, Animefan8888 said:

Look at the methods inside it there are two I can think of insertItem and extractItem. 

 

It isn't. The contents are synced from the IItemHandler when they change if you call detectAndSendChanges(I believe that is what it is called).

I think I got it... again.

 

package com.Garrett.backtobasics.blocks;

import net.minecraft.block.Block;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.ITickableTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemStackHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import static net.minecraft.util.Direction.*;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

import static com.Garrett.backtobasics.blocks.ModBlocks.AUTO_MINER_TILE_ENTITY;

public class AutoMinerTileEntity extends TileEntity implements ITickableTileEntity, INamedContainerProvider {

    private static final Logger LOGGER = LogManager.getLogger();
    private LazyOptional<IItemHandler> handler = LazyOptional.of(this::createHandler);
    private int tickCounter = 0;
    private ArrayList<String> veinBlockList = new ArrayList<>();

    public AutoMinerTileEntity() {

        super(AUTO_MINER_TILE_ENTITY);
        veinBlockList.add("backtobasics:diamond_vein");
        veinBlockList.add("backtobasics:gold_vein");
        veinBlockList.add("backtobasics:iron_vein");
        veinBlockList.add("backtobasics:redstone_vein");
    }


    // 20 ticks per second
    @Override
    public void tick() {

        tickCounter++;

        if (tickCounter >= 60) {
            tickCounter = 0;

            mineBlock();
        }
    }

    // the lazy handler postpones execution of code until it is needed for the first time and cashes it
    // so it won't be recreated every time it is used.
    private ItemStackHandler createHandler () {
        return new ItemStackHandler(1);
    }

    // reads inventory from world file on load
    @Override
    public void read(CompoundNBT tag) {
        CompoundNBT invTag = tag.getCompound("inv");
        handler.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(invTag));
        createHandler().deserializeNBT(invTag);
        super.read(tag);
    }

    // writes inventory to world file whenever world is saved
    @Override
    public CompoundNBT write(CompoundNBT tag) {
        handler.ifPresent(h -> {
            CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT();
            tag.put("inv", compound);
        });
        return super.write(tag);
    }


    // Capabilities add funcionality to blocks and items.
    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
            return handler.cast();
        }
        return super.getCapability(cap, side);
    }

    @Override
    public ITextComponent getDisplayName() {
        return new StringTextComponent(getType().getRegistryName().getPath());
    }

    @Nullable
    @Override
    public Container createMenu(int i, PlayerInventory playerInventory, PlayerEntity playerEntity) {
        return new AutoMinerContainer(i, world, pos, playerInventory, playerEntity);
    }

    private void mineBlock() {

        if (world != null) {
            if (world.getServer() != null) {
                Block block = getBlockToMine();
                BlockPos blockPos = getBlockToMinePosition();
                handler.ifPresent(h -> {
                    ItemStack stack = h.getStackInSlot(0);
                    int stackSize = stack.getCount();
                    int stackLimit = h.getSlotLimit(0);
                    ServerWorld serverWorld = world.getServer().getWorld(world.dimension.getType());
                    List<ItemStack> drops = Block.getDrops(block.getDefaultState(), serverWorld, blockPos, super.getTileEntity());
                    for (ItemStack item: drops) {
                        if ((stackSize < stackLimit && item.getItem() == stack.getItem()) || stack.isEmpty()) {
                            h.insertItem(0, item, false);
                            if (!veinBlockList.contains(block.getRegistryName().toString())) {
                                world.destroyBlock(blockPos, false);
                            }
                        }
                    }
                });
            }
        }
    }

    // gets block connected to the "drill face"
    private Block getBlockToMine() {

        if (getBlockState().getValues().containsValue(UP)) {
            return world.getBlockState(getPos().up()).getBlock();

        } else if (getBlockState().getValues().containsValue(DOWN)) {
            return world.getBlockState(getPos().down()).getBlock();

        } else if (getBlockState().getValues().containsValue(NORTH)) {
            return world.getBlockState(getPos().north()).getBlock();

        } else if (getBlockState().getValues().containsValue(SOUTH)) {
            return world.getBlockState(getPos().south()).getBlock();

        } else if (getBlockState().getValues().containsValue(EAST)) {
            return world.getBlockState(getPos().east()).getBlock();

        } else {
            return world.getBlockState(getPos().west()).getBlock();
        }
    }
    // gets block connected to the "drill face"
    private BlockPos getBlockToMinePosition() {

        if (getBlockState().getValues().containsValue(UP)) {
            return getPos().up();

        } else if (getBlockState().getValues().containsValue(DOWN)) {
            return getPos().down();

        } else if (getBlockState().getValues().containsValue(NORTH)) {
            return getPos().north();

        } else if (getBlockState().getValues().containsValue(SOUTH)) {
            return getPos().south();

        } else if (getBlockState().getValues().containsValue(EAST)) {
            return getPos().east();

        } else {
            return getPos().west();
        }
    }
}

 

Edited by andGarrett
Link to comment
Share on other sites

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



×
×
  • Create New...

Important Information

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