Development Assistance Get the entity that killed a player? [SOLVED]

Discussion in 'Plugin Help/Development/Requests' started by TheMrJezza, Mar 17, 2015.

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

    TheMrJezza

    Hello I have a problem with checking for an enderman, I want players who are killed by an enderman to keep their inventory, here is some of my code:
    Code:
        @EventHandler
        public void onDeath(PlayerDeathEvent e) {
            if (((e.getEntity().getKiller() instanceof Enderman))
                    && (e.getEntityType() == EntityType.ENDERMAN)) {
                e.setKeepInventory(true);
            }
        }
    }
    That doesn't work and I have also tried this:
    Code:
        @EventHandler
        public void onDeath(PlayerDeathEvent e) {
            if (((e.getEntity().getKiller() instanceof Enderman))
                    && (e.getEntity().getKiller() != null))
                e.setKeepInventory(true);
        }
    }
    Can someone please tell me what I'm doing wrong?
     
  2. Offline

    pie_flavor

    @TheMrJezza Also use Player#getLastDamageCause() and make sure the player was actually killed as opposed to dying (e.g. cactus, fall, void, etc.), as #getKiller() returns the last killer, not necessarily the last death
     
    TheMrJezza likes this.
  3. Offline

    TheMrJezza

    @pie_flavor I have been told to use Player#getLastDamageCause once before, but I searched google and couldn't find anything, and I didn't understand the Javadocs, I have never used Player#getLastDamageCause and I can't really see the obvious with this, would you mind giving me an example just so I can see how to do it?

    Also would I have to change anything to
    Code:
    @EventHandler
    public void onDeath(PlayerDeathEvent e) {
     
    Last edited: Mar 18, 2015
  4. Offline

    Konato_K

    @TheMrJezza getLastDamageCause returns an EntityDamageEvent which can be an EntityDamageByEntityEvent, if this is the case you can use getDamager to get the last thing that damaged the player and check if it's an Enderman, the problem with getKiller is that it always returns a Player, so if they are not killed by a player it won't work.
     
  5. Offline

    TheMrJezza

    I got my answer, thank you both though, you said everything right, I just found an example that helped me understand how to put it:
    Code:
        @EventHandler
        public void onPlayerDeath(PlayerDeathEvent event) {
            Player player = event.getEntity();
            if (event.getEntity().getLastDamageCause() instanceof EntityDamageByEntityEvent) {
                EntityDamageByEntityEvent nEvent = (EntityDamageByEntityEvent) event
                        .getEntity().getLastDamageCause();
    
                if ((nEvent.getDamager() instanceof Enderman)) {
    
     
    Konato_K likes this.
Thread Status:
Not open for further replies.

Share This Page