Easyest way to get item max durability.

Discussion in 'Plugin Development' started by ParkourGrip, Feb 5, 2012.

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

    ParkourGrip

    How can i get items max durability before it brakes?
     
  2. Offline

    Slayer9x9

    I suppose you could set the event to be canceled, then parse the event parameter to another method in which you could determine the max durability.
     
  3. Offline

    Roadkill909

    First get the item id. If you're using the ItemStack class use this:

    int id = ItemStack.getTypeID();
    Material mat = Material.getMaterial(id);

    Once you have the material, or if you started with the material, use this method:

    short max = mat.getMaxDurability();

    It's a short integer, so if you plan to do a lot of math with it, you'll have to do some casting.

    The events to check before an item breaks are EntityDamageByEntityEvent and BlockBreakEvent. Not sure if there is a EntityDamageByPlayerEvent, but if there's not, get the damage source in the entity, and check if it's an instanceof Player. Here's a sample:

    Code:Java
    1.  
    2. @EventHandler
    3. public void onBlockBreak(BlockBreakEvent event){
    4. ItemStack item = event.getPlayer().getItemInHand();
    5. if(item==null)return;
    6. short max = item.getType().getMaxDurability();
    7. //do whatever here
    8. }
    9.  
    10. @EventHandler
    11. public void onEntityDamageByEntity(EntityDamageByEntityEvent event){
    12. if(!(event.getDamager() instanceof Player))return;
    13. ItemStack item = ((Player) event.getDamager()).getItemInHand();
    14. if(item==null)return;
    15. short max = item.getType().getMaxDurability();
    16. //do whatever here
    17. }
     
    leimekiller and ams2990 like this.
  4. Offline

    Roadkill909

    I hate to necropost a two year old thread, but according to the site I recently got a like from leimekiller

    If my comment helped you, that's cool, but I figured I'd let you know that in that long timeframe Bukkit has changed a bit. There is now a much easier way to this via an Event called PlayerItemBreakEvent. The JavaDoc can be found here:
    http://jd.bukkit.org/rb/apidocs/org/bukkit/event/player/PlayerItemBreakEvent.html

    Also there is a shorter way to get the Material in one less line of code using itemStack.getType(). getTypeID() and use of numerical ids for items has been deprecated, as Mojang/Bukkit is phasing that out.

    Anyway, hope it helps.
     
Thread Status:
Not open for further replies.

Share This Page