如何更换库存中的物品? (1.16.5)

How to replace an item in inventory? (1.16.5)

我希望在覆盖的函数触发时用另一个项目替换该项目。

    @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);
    }

我怎样才能做到这一点?

注意:我使用的是 MCP 映射。

您应该更改 stack 项。示例:

@Override
public ActionResultType itemInteractionForEntity(ItemStack stack, PlayerEntity playerIn, LivingEntity target, Hand hand) {
    if (!playerIn.world.isRemote()) {
        stack = myNewItem;
        // or just directly edit item:
        stack.setAmount(1); // example
    }
    return super.itemInteractionForEntity(stack, playerIn, target, hand);
}

我已经做到了:

// 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);
}