remove entity doesn't seem to work

Discussion in 'Plugin Development' started by C4TALYST, Jul 16, 2022.

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

    C4TALYST

    upload_2022-7-16_22-54-2.png



    Here i want to despawn an entity when it is hit by a player holding a specific item. It doesn't seem to work.

    i need help.
    now
     
  2. Offline

    gochi9

    I'm pretty sure getItemInUse() doesn't work in this case so you should have a "null" print in your console. You can get the weapon by using player.getInventory().getItemInMainHand() because you cannot do melee attacks with your off-hand so a melee weapon will always be in your right (main) hand.

    Also don't use ItemMeta.equals just use item1.isSimilar(item2) but if you really must compare just two item metas then Bukkit has a thing for this:

    Code:
    Bukkit.getItemFactory().equals(item1.getItemMeta(), item2.getItemMeta())
    Lastly you should check if the damaged entity is another player because if you try to use the remove() method on a player the server isn't going to be happy about that.
     
  3. Offline

    Strahan

    Minor nitpick but checking if e.getEntity() is an Entity, and casting it thus, is pointless as that method returns an Entity by default. Also getItemMeta() is @Nullable, so don't hang methods off of it without checking first.
     
  4. Offline

    gochi9

    Indeed I did not see that he is checking if the e.getEntity() is an Entity, he could use this to check if e.getEntity() is not a player so he can avoid accidentally using .remove() on a player.

    Also I shoud've mentioned to check if the item meta is null but I didn't since Bukkit.getItemFactory().equals(meta1, meta2) can take null values but yeah you should check if the meta is null in most cases.

    Lastly the code could be made to look a tiny bit cleaner.
    Code:
        @EventHandler
        public void stickHit(EntityDamageByEntityEvent ev) {
            if(ev.getEntity() instanceof Player || !(ev.getDamager() instanceof Player))
                return;
       
            Entity damaged = ev.getEntity();
            Player damager = (Player) ev.getDamager();
            ItemStack item = damager.getInventory().getItemInMainHand();
       
            if(item == null)
                return;
       
            if(!item.isSimilar(someOtherItem))
                return;
       
            //OR IF YOU WANT JUST TO CHECK THE ITEM META
       
            //Again as explained above this can take null values
            //But if you compare 2 completly different items that don't have an ItemMeta than this will still return true
            //So you could check if either ItemMeta is null and then use this
    
            if(!Bukkit.getItemFactory().equals(item.getItemMeta(), nulsomeOtherItem.getItemMeta()))
                return;
    
            someCoolStuff();
        }
    
     
Thread Status:
Not open for further replies.

Share This Page