How to ensure if a player is online/exists

Discussion in 'Bukkit Help' started by HorseNuggets, Nov 24, 2017.

Thread Status:
Not open for further replies.
  1. Offline

    HorseNuggets

    I have a command on my server called /coords <player> and it will tell you the coordinates of the player. The only problem is that when you input the name of a player that isn't currently online, it returns an internal error. Is there a way to check if the player is online/exists so I can return the code? Thanks

    Here is the code:
    Code:
            if(cmd.getName().equalsIgnoreCase("coords")){
             
                if (args.length == 1) {
                 
                    Player player = (Player) sender;
                    Player player2 = Bukkit.getServer().getPlayer(args[0]);
                    String bna = args[0].toString();
                 
                    if (player2 == null) return true;
                 
                    int x1 = (int)Math.round(Double.valueOf(player.getLocation().getX()));
                    int y1 = (int)Math.round(Double.valueOf(player.getLocation().getY()));
                    int z1 = (int)Math.round(Double.valueOf(player.getLocation().getZ()));
                 
                    int x2 = (int)Math.round(Double.valueOf(player2.getLocation().getX()));
                    int y2 = (int)Math.round(Double.valueOf(player2.getLocation().getY()));
                    int z2 = (int)Math.round(Double.valueOf(player2.getLocation().getZ()));
                 
                    double ddistance = Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2) + Math.pow((z2 - z1), 2));
                    int distance = (int)Math.round(ddistance);
                 
                    sender.sendMessage(ChatColor.GRAY + bna + ": " + ChatColor.YELLOW + x2 + " " + y2 + " " + z2 + " (" + distance + "m)");
                    return true;
                }
             
                sender.sendMessage(ChatColor.GRAY + "Usage: " + ChatColor.YELLOW + "/coords <player>");
             
                return true;
            }
    EDIT: ok it works now, I just added the if (player2 == null) return true;
    I honestly didn't think that would work lol
     
    Last edited: Nov 24, 2017
  2. Offline

    timtower Administrator Administrator Moderator

    @HorseNuggets getPlayer returns null when the player is not online.
    But the error tells the issue, please post it.
     
Thread Status:
Not open for further replies.

Share This Page