How to count a players in region (WorldGuard)

Discussion in 'Plugin Development' started by nnx, Jun 26, 2020.

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

    nnx

    PS English from Google Translate

    Hello. Good night! I would like to know how it is possible to count players in a certain region (WorldGuard). I've been trying to do this for some time but I couldn't.
     
  2. @nnx
    I've done some digging, can't actual test this code but in theory it should work, hopefully

    You will need both worldguard and worldedit

    Code:java
    1. //Getting the WorldGuard instance
    2. WorldGuard wg = WorldGuard.getInstance();
    3. //Getting the region manager
    4. RegionManager rm = wg.getPlatform().getRegionContainer().get(BukkitAdapter.adapt(Bukkit.getWorld("world")));
    5. //Getting a region with the id of 'region1'
    6. ProtectedRegion region = rm.getRegion("region1");
    7. //Converting the WorldGuard region to a WorldEdit region
    8. Polygonal2DRegion weRegion = new Polygonal2DRegion(BukkitAdapter.adapt(Bukkit.getWorld("world")), region.getPoints(), region.getMinimumPoint().getBlockY(), region.getMaximumPoint().getBlockY());
    9. //Player Counter
    10. int playerCount = 0;
    11. //Looping over all the blocks (including air) in the region
    12. for(BlockVector3 block : weRegion) {
    13. //Getting the location of the current block in the loop
    14. Location loc = new Location(Bukkit.getWorld("world"), block.getBlockX(), block.getBlockY(), block.getBlockZ());
    15. //Looping over every online player
    16. for(Player p : Bukkit.getOnlinePlayers()) {
    17. //Checking if players location is equal to the location of the block in the region
    18. if(p.getLocation().equals(loc)) {
    19. playerCount++;
    20. }
    21. }
    22. }


    I'm sure theres a much easier way but im not sure :p
     
  3. Offline

    nnx

    PS English From Google Translate

    This is for WorldGuard 7.0. My application is for version 1.8 of minecraft (WorldGuard 6.x). Could you help me adapt this code for WorldGuard version 6.X? Thank you
     
    Last edited: Jun 29, 2020
  4. @nnx

    Code:java
    1.  
    2. WorldGuardPlugin wg = WorldGuardPlugin.inst();
    3.  
    4. RegionManager rm = wg.getRegionManager(Bukkit.getWorld("world"));
    5.  
    6. ProtectedRegion region = rm.getRegion("region1");
    7.  
    8. int playerCount = 0;
    9.  
    10. for (Player p : Bukkit.getOnlinePlayers()) {
    11. if(region.contains(p.getLocation().getBlockX(), p.getLocation().getBlockY(), p.getLocation().getBlockZ()))
    12. playerCount++;
    13. }
    14.  
     
Thread Status:
Not open for further replies.

Share This Page