Search code examples
javaminecraftminecraft-forge

Trying to detect if the player has a specific item in their inventory in my Minecraft mod


I'm making my Minecraft mod and I'm trying to detect if a player has a specific item, which would give you an effect if you have it. I'm trying to do this by using PlayerTickEvent, but I don't know how to use it, since I haven't used it before. I used a function that checked which slot was changed for an enchant before, so I tried that, but it didn't work. any ideas?

This is the code I originally tried:

@SubscribeEvent
public void testItemFunction(LivingEquipmentChangeEvent event) {
    boolean itemIsInInventory;
    Object player = event.getEntityLiving();
    if (event.getEntityLiving() instanceof EntityLivingBase) {
        EntityEquipmentSlot slotChanged = event.getSlot();
        if (slotChanged.getSlotIndex() > -1 && slotChanged.getSlotIndex() < 36) {
            if(slotChanged != null && slotChanged.() == ModItems.TEST_ITEM) {
                itemIsInInventory = true;
            }
        } else {
            itemIsInInventory = false;
        }
    }
}

instead of setting and removing an effect as the result I'm changing the variable itemIsInInventory because I'm making this method in a class in my util package so I can call it whenever I want instead of copy-pasting the method


Solution

  • I found a much simpler answer to this, but it might not work for certain things. I found this a while ago, but it didn't seem to work, so I looked for another solution, but now that I came back to it I realized I just did it wrong. this is the code:

    @Override
        public void onUpdate(ItemStack itemstack, World world, Entity entity, int i, boolean flag)
        {
            //Runs the method every tick the item is in the player's inventory
            ((EntityLivingBase) entity).addPotionEffect(new PotionEffect(MobEffects.INVISIBILITY, 10, 0, false, false));
            //Gives the entity with the item the invisibility effect for half a second every tick
        }
    

    Put simply, instead of detecting whether or not a player has the item, it only runs the code when the player has the item. What I meant by "I did it wrong" is that this code should be put in the item's class, so that it only triggers when the item is in your inventory. I'm not sure, but I don't think this would work if giving the item to, say, a zombie.