FIXED
I am attempting to add a health bar next to my entities name, like:
Level 3 Skeleton ||||
Where bars are how much health, out of 5. I have tried everything it seems, but I cannot figure it out! I think its really simple, but I just can't get it...
@EventHandler
public void entityDamageEntity(EntityDamageEvent event) {
LivingEntity entity = (LivingEntity) event.getEntity();
if (entity.getCustomName() != null) {
entity.setCustomName(entity.getCustomName().replaceAll("|", ""));
int health = (int) Math.ceil(entity.getHealth() / entity.getMaxHealth() * 5);
int i = 1;
String healthbar = " |";
while(i < health){
i++;
healthbar = healthbar + "|";
}
entity.setCustomName(entity.getCustomName() + healthbar);
}
}
I just cannot seem to get it to work! It does weird things, try using it with a named entity. If someone could point out the error, that would be great =D
https://i.stack.imgur.com/RYdcI.png
FIXED CODE:
@EventHandler
public void entityDamageEntity(EntityDamageEvent event) {
LivingEntity entity = (LivingEntity) event.getEntity();
if (entity.getCustomName() != null) {
entity.setCustomName(entity.getCustomName().replaceAll("\\|", ""));
int health = (int) ((float) entity.getHealth() / entity.getMaxHealth() *5);
if (health > 0){
char[] bars = new char[health + 1];
Arrays.fill(bars, '|');
entity.setCustomName(entity.getCustomName() + " " + new String(bars));
entity.setCustomName(entity.getCustomName().replaceAll(" ", " "));
} else {
entity.setCustomName(entity.getCustomName());
entity.setCustomName(entity.getCustomName().replaceAll(" ", " "));
}
}
}