Solved Help with a PlayerMoveEvent

Discussion in 'Spigot Plugin Development' started by 2GramsIn, Jul 8, 2021.

  1. Hello. What I am trying to do is that the block that you are stopped is only shown once. But if it changes, the new block is shown without repeating itself.

    I haven't written in Java in a long time. But I have knowledge of LUA. I think the problem is that the variable is not rewritten and therefore the conditional will always be true.

    Thank you for reading

    Code (Java):
        @EventHandler
        public static void  onPlayerMove(PlayerMoveEvent event){
            Player player = event.getPlayer();
            int x = player.getLocation().getBlockX();
            int y = player.getLocation().getBlockY();
            int z = player.getLocation().getBlockZ();


            Material lastBlock;
            Material block = player.getWorld().getBlockAt(x,y - 1,z).getType();

            if (block != lastBlock) {
                player.sendMessage("You are on: " + block);
                lastBlock = block;

            }
        }
     
  2. How should this work? lastBlock will always be null!
    Don't define lastBlock as a local variable!
     
  3. When using PlayerMoveEvent, you should use event.getTo() or even.getFrom() instead of player.getLocation().
    The reason it's not working is because lastBlock is a local variable - it's lost after each movement. You can either check the block type of the From location and compare it to the To location, or keep a HashMap of the last Material each player was standing on.
     
    • Agree Agree x 1
    • Winner Winner x 1
  4. Thanks! It has worked. The problem was the variable that was in local