Solved [EntityDeathEvent] Some way to get the killer entity

Discussion in 'Spigot Plugin Development' started by _xTsunamix_, Mar 13, 2020.

  1. I see that it is possible to obtain the killer if it is a player, but I would like to obtain the killer entity

    For example if a zombie kills a snowman I want to get the zombie.

    Code (Java):

      @EventHandler
      public void onEntityDeathEvent(EntityDeathEvent event) {
        Player playerKiller = event.getEntity().getKiller(); // event.getEntity().getKiller() only get Player object
     
        Entity entityKiller = event.getEntity().getKiller(); // i need this but it doesn't work
      }
     
    I am really programming with javascript thanks to ScriptCraft but there is no problem if you give me examples in Java because I can understand it since I can use any object or method of Bukkit / Spigot and plugins and I can even use the Java api

    My code (JS):
    Code (Text):

    events.on(bkEvent.entity.EntityDeathEvent, function(event, cancel) {
      console.log(event.getKiller());

      if(!(event.getEntity().getLastDamageCause().getCause() === bkDamageCause.ENTITY_ATTACK)) {
        return;
      }
    });
     


    Any way to achieve the goal of obtaining the killer entity?
     
    #1 _xTsunamix_, Mar 13, 2020
    Last edited: Mar 13, 2020
  2. Code (Text):
    event.getEntity().getLastDamageCause().getDamager()
    Entity#getLastDamageCause() returns the last called EntityDamageEvent.

    getDamager() is a method from EntityDamageByEntityEvent which extends EntityDamageEvent.
     
    • Agree Agree x 3
  3. Choco

    Moderator

    Yes, though you should check for nullability. If the entity dies but was not damaged, null will be returned and you're just asking for an NPE. Get it, check it and use it. Is it likely to happen? No absolutely not. Is it possible? In an environment where plugins can do anything they want, yes.
     
    • Like Like x 1
  4. Thanks to you it is already resolved. Greetings.
     
  5. Thank you also for your response. I will take into account what you tell me. I needed to get the killer entity for check if it is a player, if not cancel

    My code (It is already solved thanks to Plochem):
    Code (Text):

    events.on(bkEvent.entity.EntityDeathEvent, function(event, cancel) {

      if(!(event.getEntity().getLastDamageCause().getCause() === bkDamageCause.ENTITY_ATTACK)) {
        return;
      }

      if(!(event.getEntity().getLastDamageCause().getDamager().getType() === bkEntity.EntityType.PLAYER)) {
        return;
      }

      var player = event.getEntity().getKiller();

      echo(player, 'OK you are a player');

    });