Remove item on right click with other item

Discussion in 'Plugin Development' started by yupie_123, Apr 6, 2014.

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

    yupie_123

    So I have an event set in which if the player clicks a wooden hoe and he has at least one snowball in his inventory, one snowball gets removed. So if a player has 30 snowballs and he right clicks the hoe, he will only have 29 left.
    I was messing around with this for a while but couldn't find a solution.

    My Code:
    Code:java
    1. if (player.getItemInHand().getType() == Material.WOOD_HOE){
    2. if(player.getInventory().contains(Material.SNOW_BALL, 1)){
    3. player.getInventory.removeItem(new ItemStack(Material.SNOW_BALL, 1));
    4. }else{
    5. player.sendMessage("You don't have enough snowballs");
    6. }
    7. }
     
  2. Offline

    StaticJava

    What is the error/StackTrace?

    I notice immediately that you aren't checking if the Action is a right click.
     
  3. Offline

    Barnyard_Owl

    yupie_123
    You need parentheses after getInventory, because it is a method. If you use a smart IDE, (ex. eclipse) it would point this out. :)
    player.getInventory()...
     
  4. Offline

    StaticJava


    You're right. I didn't immediately catch that, lol.
     
  5. Offline

    yupie_123


    Oh woops, I had it set correctly in my code, I think I messed up copying and pasting.


    But what if it doesn't matter if it's a right click or a left click? I want both ways to work. Do I still need to do that?

    About the error, well I simply don't get any, it just doesn't remove the snowballs from the inventory.
     
  6. yupie_123
    I think I got it.
    Code:
    player.getInventory.removeItem(new ItemStack(Material.SNOW_BALL, 1));
    It removes the ItemStack if it matches with precision, ie both material and count.
    Try
    Code:
    ItemStack item = player.getInventory.first (Material.SNOW_BALL);
    item.setCount(item.getCount()-1);
    Also, maybe
    Code:
    player.getInventory().containsAtLeast()
    may be better.

    Checkout this link.
    http://forums.bukkit.org/threads/remove-one-item-from-stack-custom-item.252982/
     
  7. Offline

    StaticJava

    I thought you only wanted right click. In that case, try Hartorn's suggestion.
     
  8. Offline

    yupie_123

    That doesn't seem to work, it says that I need to change the type from ItemStack to int but when I do that I can't use item.setCount
     
  9. yupie_123 : Yeah sorry,
    Code:
    ItemStack item =  player.getInventory().getItem(player.getInventory().first (Material.SNOW_BALL));
    First only returns the index.
    Also, better to add a test like that.
    Code:
    if(item.getCount() ==1)
    {
    player.getInventory.remove(item)
    }
    else
    {
    item.setCount(item.getCount()-1)
    }
     
  10. Offline

    yupie_123

    Ok yeah, it all works now, thanks!
     
Thread Status:
Not open for further replies.

Share This Page