Finding an item (w/DisplayName) in a player's inventory

Discussion in 'Plugin Development' started by kunhunjon, Jun 24, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    kunhunjon

    Does anyone know how I could find a specific custom item with a display name in a player's inventory during the playerinteractevent.

    Code:java
    1. int slot = event.getPlayer().getInventory().first(bullet);
    2. int bullets = event.getPlayer().getInventory().getItem(slot).getAmount();


    The item is acting as Ammo for a custom weapon. I can't seem to find any amount of the "bullet" in the inventory. I've even tried getting the inventory contents and running a loop to check if the item has the specific display name or a matching ItemMeta. It still never finds the bullets. I think it has something to do with ItemMeta itself. With the method I use above I just get Null pointers, even if I have the custom bullet item in my inventory.
     
  2. Offline

    THEREDBARON24

    What is the item supposed to be? You could try and be more specific by using that first, however, this should work. Make sure to change the "bullet" string to whatever you are specifically using. Finally, make sure to update the inventory. I had an issue like this before.
    Code:java
    1. for(ItemStack item : player.getInventory().getContents()){
    2. if(item.getItemMeta().getDisplayName().equals("Bullet")){
    3. //code here
    4. }
    5.  
    6. }

    And no, my spacing is never this bad :p
     
  3. Offline

    kunhunjon


    It's supposed to be a button named "Bullet". Im trying to use it as ammo that decreases with use. So I have to find any amount of the bullet in the players inventory and take one from it every time player interact event runs and the user is holding the gun. That is exactly what I think I need, I might have tried it though, not sure. I'll try this and see if it gets any results.
     
  4. Offline

    izarooni

    kunhunjon
    The loop THEREDBARON24 gave you doesn't check for null items and items that don't have dispaly name which will give you null errors in the console.
     
  5. Offline

    kunhunjon

    izarooni You're a hero. So I should check if each element in the array is not null then do .hasDisplayName. Will .getContents return the number of items in each ItemStack as well as let me fiddle around with the stack?
     
  6. Offline

    izarooni

    you would do item.getAmount() to get the number of items in each ItemStack
     
  7. Offline

    kunhunjon

    Okay great! Thanks for all the help :)
     
Thread Status:
Not open for further replies.

Share This Page