Search code examples
javapluginsbukkit

Spigot Jump Detection Returning NullPointerException


I am trying to detect when the player jumps, but I keep getting a NullPointerExeption, and I don't know what is causing it. Here is my code

private Map<Player, Double> playerY = new HashMap<>();

@org.bukkit.event.EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
    if (event.getPlayer().getLocation().getY() > playerY.get(event.getPlayer())
      && event.getPlayer().getWorld().getBlockAt((int)event.getPlayer().getLocation().getX(), (int)(event.getPlayer().getLocation().getY() - 0.2), (int)event.getPlayer().getLocation().getZ()).getType() == (Material.AIR)) {
        //My Code
    }    
}

I know I probably missing something really obvious here but I can't figure out why I am getting a NullPointerException.


Solution

  • You haven't provided enough details; you should read 'How do I ask a good question?'. However, it's likely that your NullPointerException is happening because the following will return null if the key doesn't exist in the map.

    playerY.get(event.getPlayer())
    

    You do not show us in the code when or if you ever add the player to your map. You could fix this by first checking if the player exists in the map before trying to retrieve data that might not exist.

    Alternatively; if you're just trying to detect a jump, rather than store the players last Y value which I assume you are going to do, you can use the information already provided by the PlayerMoveEvent. The event has getFrom() and getTo() methods. You could check if the getY() from the to location is greater than the getY() value from the from location.