Skip to content

Instantly share code, notes, and snippets.

@Jikoo
Created January 14, 2016 17:15
Show Gist options
  • Save Jikoo/72ff075e1be3bc29d2cb to your computer and use it in GitHub Desktop.
Save Jikoo/72ff075e1be3bc29d2cb to your computer and use it in GitHub Desktop.
Manage name tag visibility for scoreboards
package com.github.jikoo;
import java.util.HashMap;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.scoreboard.NameTagVisibility;
import org.bukkit.scoreboard.Team;
/**
* Utility for managing nametag visibility for invisible players
*
* @author Jikoo
*/
public class InvisibilityManager {
private final HashMap<UUID, BukkitTask> tasks;
private final JavaPlugin plugin;
public InvisibilityManager(JavaPlugin plugin) {
tasks = new HashMap<>();
this.plugin = plugin;
}
/**
* Update the Player specified's nametag on a tick delay. Allows per-gamemode stuff to finish beforehand.
*
* @param player the Player to update
*/
public void lazyVisibilityUpdate(Player player) {
final UUID uuid = player.getUniqueId();
new BukkitRunnable() {
@Override
public void run() {
Player player = Bukkit.getPlayer(uuid);
if (player == null) {
return;
}
updateVisibility(player);
}
}.runTaskLater(plugin, 1L);
}
public void updateVisibility(Player player) {
if (tasks.containsKey(player.getUniqueId())) {
tasks.remove(player.getUniqueId()).cancel();
}
if (!player.hasPotionEffect(PotionEffectType.INVISIBILITY)) {
setVisible(player);
return;
}
for (PotionEffect potion : player.getActivePotionEffects()) {
// Note: PotionEffectType is not actually an Enum, you muse use .equals to compare.
if (potion.getType().equals(PotionEffectType.INVISIBILITY)) {
setInvisible(player, potion.getDuration());
break;
}
}
}
private void setInvisible(Player player, int duration) {
Team team = player.getScoreboard().getEntryTeam(player.getName());
if (team == null) {
// TODO Team has not been set up, implement a method to do so.
team = player.getScoreboard().getEntryTeam(player.getName());
}
team.setNameTagVisibility(NameTagVisibility.NEVER);
final UUID uuid = player.getUniqueId();
tasks.put(uuid, new BukkitRunnable() {
@Override
public void run() {
tasks.remove(uuid);
Player player = Bukkit.getPlayer(uuid);
if (player != null) {
updateVisibility(player);
}
}
}.runTaskLater(plugin, duration));
}
private void setVisible(Player player) {
Team team = player.getScoreboard().getEntryTeam(player.getName());
if (team == null) {
// TODO Team has not been set up, implement a method to do so.
team = player.getScoreboard().getEntryTeam(player.getName());
}
team.setNameTagVisibility(NameTagVisibility.ALWAYS);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment