Can't send message to player on death event

I’m not sure what I’m doing wrong.

public class CustomDeathMessage
{
    @Listener
    public void onPlayerDeath(DestructEntityEvent.Death event)
    {
        final Optional<Entity> opt = event.getCause().first(Entity.class);
        if (!opt.isPresent())
        {
            return;
        }
        final Player player = (Player)opt.get();
        
        player.sendMessage(Text.of("You Died!"));
    }
}

First make sure you register the listener class in your main plugin class. Now you’re trying to cast a player from an entity which the entity which has died might not always be a player. So instead you should be using:

final Optional<Player> opt = event.getCause().first(Player.class);

I would also recommend using the @First annotation which would clean up the code and your listener will only be called if a player is found in the cause. The annotation would be used as such:

public class CustomDeathMessage
{
    @Listener
    public void onPlayerDeath(DestructEntityEvent.Death event, @First Player player)
    {
        player.sendMessage(Text.of("You Died!"));
    }
}
1 Like

Yes, it’s been registered from the main class. I used getConsole.sendMessage() to make sure.

I tried this:

public class CustomDeathMessage
{
    @Listener
    public void onPlayerDeath(DestructEntityEvent.Death event, @First Player player)
    {
        player.sendMessage(Text.of("You Died!"));
    }
}

This didn’t send any message to the player.

Actually, in DestructEntityEvent.Death, the entity probably doesn’t appear in the cause. In fact, it’s a getter in the event.
Here’s code that should work:

@Listener
public void onDeath(DestructEntityEvent.Death e, @Getter("getTargetEntity") Player p) {
    p.sendMessage(Text.of("You Died!"));
}

The @Getter is used because in this case, getTargetEntity() returns a Living, and this casts to Player (or doesn’t call it if that’s not possible).

1 Like

Oh right silly me, I actually use that in one of my recent plugins, I was in a bit of a hurry at the time to do something and didn’t actually get the chance to check. Thanks for correcting that for me :stuck_out_tongue:

1 Like

I will try tomorrow. Also, how do you find all this information, javadocs?

Thank you, you guys are amazing.

Trial, error, Sponge Docs, and JavaDocs.

1 Like