Solved Get location of offline player

Discussion in 'Plugin Development' started by The_Spaceman, Oct 22, 2019.

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

    The_Spaceman

    Hello,

    I'm looking for the location of an offline player and this does not work:
    Code:java
    1. Player offlinePlayer = Bukkit.getOfflinePlayer(playerUUID).getPlayer();
    2. offlinePlayer.loadData();
    3. offlinePlayer.getLocation();

    .getPlayer() returns a null value.
    And the UUID was of a player who played before but was not online

    Is there another way? Of should I save all the locations of the players like this:
    Code:java
    1. import org.bukkit.Bukkit;
    2. import org.bukkit.Location;
    3. import org.bukkit.OfflinePlayer;
    4. import org.bukkit.event.EventHandler;
    5. import org.bukkit.event.Listener;
    6. import org.bukkit.event.player.PlayerJoinEvent;
    7. import org.bukkit.event.player.PlayerLoginEvent;
    8. import org.bukkit.event.player.PlayerQuitEvent;
    9.  
    10. import java.util.HashMap;
    11. import java.util.UUID;
    12.  
    13. public class OfflineLocationManager implements Listener {
    14.  
    15. public static HashMap<UUID, Location> locMap = new HashMap<>();
    16.  
    17. @EventHandler
    18. public void onJoin(PlayerJoinEvent e) {
    19. locMap.remove(e.getPlayer().getUniqueId());
    20. }
    21. //which is better? PlayerJoinEvent or PlayerLoginEvent?
    22. public void onJoin(PlayerLoginEvent e) {
    23. locMap.remove(e.getPlayer().getUniqueId());
    24. }
    25.  
    26. @EventHandler
    27. public void onLeave(PlayerQuitEvent e) {
    28. locMap.put(e.getPlayer().getUniqueId(), e.getPlayer().getLocation());
    29. }
    30.  
    31. public static Location getLocation(UUID uuid) {
    32. OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
    33. if (player.isOnline()) {
    34. return player.getPlayer().getLocation();
    35. } else if (player.hasPlayedBefore()) {
    36. return locMap.getOrDefault(player.getUniqueId(), null);
    37. } else {
    38. return null;
    39. }
    40. }
    41.  
    42. public static void saveMap() {
    43. //save
    44. }
    45. public static void loadMap() {
    46. //load
    47. }
    48. }


    Thank you
     
  2. Offline

    Strahan

    the .getPlayer() method only returns a Player if said user is online. I don't know how one gets a location for an offline player, if it's possible at all.

    The log at quit method seems reasonable, it's what Essentials does after all. I wouldn't screw with a map at all though, I'd just use straight config. You don't have to worry about a crash making you lose data then, and as config is cached it isn't a performance hit to query it.

    PS PlayerJoinEvent is what you want, not LoginEvent.
     
  3. Offline

    The_Spaceman

    Alright, thank you!
     
Thread Status:
Not open for further replies.

Share This Page