Question

What is the correct usage of for (Player p : ) if I am trying to get the player's location and teleport them within a Bukkit scheduled task? It gives me an unidentified error when using a : which I believe I need to connect the reset of the statement together, but there may be another way. Although this is a Minecraft Bukkit-related question, I'm sure someone here is able to help me out.

Current code:

private void teleporter()
  {
    if (getConfig().getBoolean("teleport")) {
      Bukkit.getScheduler().scheduleSyncRepeatingTask(this,
        new Runnable()
        {
          public void run() {
            for (Player p : ) {
              if (p.getLocation().getY() <= 0.0D)
              {
                p.teleport(NoVoid.spawnLocation);
                p.setFallDistance(0.0F);
              }
            }
          }
        }, 0L, 100L);
    }
  }

Any help is appreciated!

Update:

Rusher and rgettman had the right idea. Had to add Bukkit.getServer().getOnlinePlayers() to get all of the online players (had to connect it to a list).

Was it helpful?

Solution

Take your code:

for (Player p : ) {
    if(p.getLocation().getY() <= 0.0D)
        p.teleport(NoVoid.spawnLocation);
        p.setFallDistance(0.0F);
}

If you were to read this in English, it would sound like this:

  • For each player in , if that player's y-coordinate is less than or equal to zero, teleport the player back to spawn. They take no fall damage.

Do you see the obvious grammar mistake? For each player in WHAT? If you meant to say "For each player in the list of players". That might look like this:

for (Player p : listOfPlayersInTheGame) {

The variable listOfPlayersInTheGame must be a collection of players. Valid examples include but are not limited to:

  • List<Player>
  • Player[]
  • ArrayList<Player>
  • LinkedList<Player>

On another note, I don't imagine you want your teleporter to teleport ALL players on the server. You probably meant to only grab players who are currently standing on the teleporter. You might do that by taking the difference between their location and the teleporter's location in the x, y, and z planes. Obviously there is some tolerance, so we are happy if the difference is less than 1 block. For example (pseudocode):

for each player p in list:
    if Math.abs(p.x - teleporter.x) < 1:
        if(Math.abs(p.y - teleported.y) < 1):
            if(Math.abs(p.z - teleported.z) < 1):
                // They must be standing on the teleporter!
                p.teleport(spawn)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top