Solved Random teleport to player

Discussion in 'Plugin Development' started by poepdrolify, Jul 5, 2015.

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

    poepdrolify

    I'm making a plugin where you right click an item, you get teleported to a random player in the server. This is my code:
    Code:
    Random r = new Random();
    HashMap<Player, Location> plocs = new HashMap<Player, Location>();
    for(Player online : Bukkit.getServer().getOnlinePlayers()) {
        plocs.put(online, online.getLocation());
    }
    int index = r.nextInt(plocs.size());
    Location loc = plocs.get(index);
    p.teleport(loc);
    But this doesn't work. How can I get this to work?
     
  2. Any errors in the console?
     
  3. Offline

    schwabfl

    plocs' key type is Player, not int
    And you should use something like
    Code:
    p.teleport(Bukkit.getOnlinePlayers()[new Random().nextInt(Bukkit.getOnlinePlayers().length)].getLocation());
     
  4. Offline

    poepdrolify

    @schwabfl Thanks!

    @schwabfl I changed the HashMap into a ArrayList because you can also teleport to players.
    Code:
    Random r = new Random();
            ArrayList<Player> players = new ArrayList<Player>();
            for(Player online : Bukkit.getServer().getOnlinePlayers()) {
                players.add(online);
            }
            int index = r.nextInt(players.size());
            Player loc = (Player) players.get(index);
            p.teleport(loc);
    Now it works, except that I have to remove the teleported player from the list...

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 12, 2016
  5. Offline

    DoggyCode™

    I used this:
    Code:
          } else if(hand!=null&&hand.getType()==Material.COMPASS && hand.getItemMeta().getDisplayName().equals("§6Random Teleport")) {
              Random r = new Random();
              ArrayList<Player> players = new ArrayList<Player>();
              for(Player online : Bukkit.getServer().getOnlinePlayers()) {
              if(online == p) {
              }
              else
              players.add(online);
              }
              int index = r.nextInt(players.size());
              Player loc = (Player) players.get(index);
              p.teleport(loc);
              p.sendMessage("§eTelporting you to " + "§6(name)" + "§e...");
             }
    
     
  6. Offline

    Creeperzombi3

Thread Status:
Not open for further replies.

Share This Page