Setting the player's health

I have been trying to make a command that would be used as a custom suicide command within my plugin without the default Minecraft /kill command. This is what I have so far:

public class suicide implements CommandExecutor {

public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    Player player = (Player) src;
    Text text = Texts.builder("Ba.na.na").color(TextColors.GOLD).build();
    player.sendMessage(text);
    player.getHealthData().damage(20);
    return CommandResult.success();
}}

For some reason, this class sends the message to the player, but it does not modify the player’s health to reflect damage. I have also tried doing player.getHealthData().setHealth(0);, but that does not work either.

Could anyone help me find a solution for changing a player’s health data?

you need to offer() the health data back to the player. getHealthData() returns a copy

2 Likes

getHealthData is not implement yet, it’s just an abstract. Use this instead.

            Player player = (Player) src;

            HealthData healthData = player.getData(HealthData.class).get();
            healthData.setHealth(healthData.getHealth() - 20);
            player.offer(healthData);
2 Likes

Thank you very much for your help :smiley:

I got the command to work with this code:

HealthData healthData = player.getHealthData().setHealth(0);
player.offer(healthData);

It’s been implemented for a while now.

His original problem was not offering the data back.

2 Likes

This is probably more applicable for a force killing. If you want suicide what was wrong with your .damage(healthData.getHealth()) it allows for plugins to make players invulnerable preventing them from killing themselves at times where they should not be able to take damage at all.

1 Like

There is no longer “.setHealth(value)”. What to use now?

Try player.getHealthData().set(Keys.HEALTH, 1.0);

1 Like

That only sets the health in the health data, you’d need to offer it back, or simply

player.offer(Keys.HEALTH, 10D);
1 Like