Search code examples
javabukkitspigot

Bukkit Java - ArrayList is not working in Event


I want to make a plugin which gives a player night vision efect after typing a command and it is working but i also want to add if player is on this arraylist its giving an efect after dying, but it looks like after EventHandler its not loading players from arraylist.

public class Gamma implements CommandExecutor, Listener {

    private ArrayList<Player> gammaList = new ArrayList<>();

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        Player player = (Player) sender;
        PotionEffect potionEffect = player.getPotionEffect(PotionEffectType.NIGHT_VISION);
        if (gammaList.contains(player)) {
            gammaList.remove(player);
            player.sendMessage(ChatColor.GREEN + "Pomyslnie" + ChatColor.RED + " usunieto" + ChatColor.GREEN + " efekt gammy!");
            player.removePotionEffect(PotionEffectType.NIGHT_VISION);
        } else if (!gammaList.contains(player)) {
            gammaList.add(player);
            player.sendMessage(ChatColor.GREEN + "Pomyslnie" + ChatColor.DARK_GREEN + " nadano" + ChatColor.GREEN + " efekt gammy!");
            player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 1));
        }
        return true;
    }
    @EventHandler
    public void onPlayerDie(EntityResurrectEvent event) {
        
        Player player = (Player) event.getEntity();
        if (gammaList.contains(player)) {
            player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 1));
        }
    }
}

Sb know what should I change in this code?


Solution

  • I have zero experience with bukkit or spigot from a developer point of view, but given my Java experience: You're defining your ArrayList non-static, that means that it most likely isn't unique throughout the server and means that every instance of your class might have its own ArrayList. Your approach would only work if your Game class is a singleton.

    You can circumvent this by making the reference to the List static and also use a thread-safe list, like the CopyOnWriteArrayList.

    So something like:

    private static List<Player> gammaList = new CopyOnWriteArrayList<>();
    

    should work.