Search code examples
javaminecraftminecraft-forge

How to replace an item in inventory? (1.16.5)


I want the item to be replaced with an another item when the overridden function fires.

    @Override
    public ActionResultType itemInteractionForEntity(ItemStack stack, PlayerEntity playerIn, LivingEntity target, Hand hand) {

        if (!playerIn.world.isRemote()) {
            // Replace an item with xyz
        }

        return super.itemInteractionForEntity(stack, playerIn, target, hand);
    }

How can I achieve this?

Note: I'm using MCP mappings.


Solution

  • I've managed to do it like this:

    // Within your ItemA class
    @Override
    public ActionResultType itemInteractionForEntity(ItemStack stack, PlayerEntity playerIn, LivingEntity target,
        Hand hand) {
    
        // To make sure the code runs on the server
        if (playerIn.world.isRemote()) {
            return super.itemInteractionForEntity(stack, playerIn, target, hand);
        }
    
        // We check if the item is held in the main hand, if so we do the
        // main hand item sawp. This check prevents usage of the item from
        // the secondary hand too. If there was no check at all we could put
        // the item in our left hand and use it in order to get a new item in
        // our right hand.
    
        if (playerIn.getHeldItemMainhand().getItem() instanceof ItemA) {
            // ItemRegistrator just holds static refrences to all my registered items
            ItemStack itemB = new ItemStack(ItemRegistrator.ITEM_B.get()); 
    
            playerIn.setHeldItem(Hand.MAIN_HAND, itemB);
        }
    
        return super.itemInteractionForEntity(stack, playerIn, target, hand);
    }