Solved Player Interact with block

Discussion in 'Plugin Development' started by CyranoTrinity, May 10, 2015.

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

    CyranoTrinity

    I'm having some problems with player right clicking a block with bare hands.
    I'm trying to make it such that when a player right clicks a block with bare hands, it gets the block and set it in player's inventory.

    Code:
    @EventHandler
        public void onBlockClick(PlayerInteractEvent event) {
            if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
                Player player = (Player) event.getPlayer();
                Material clicked = event.getClickedBlock().getType();
                if(player.getItemInHand().getType() == Material.AIR) {
                    player.getItemInHand().setType(clicked);
                    player.sendMessage("debug");
                }
              
                player.getItemInHand().setType(clicked);
              
                event.setCancelled(true);
              
            }
        }
    This is my current code. The debug message appears but the block is not set.
     
  2. .getItemInHand() returns a copy of the item.
    You need to use setItemInHand and create a new itemstack for that
     
  3. Offline

    CyranoTrinity

    @FisheyLP Thanks, I realized it just before you posted it.
    This is fixed code:
    Code:
    @EventHandler
        public void onBlockClick(PlayerInteractEvent event) {
            if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
                Player player = (Player) event.getPlayer();
                Material clicked = event.getClickedBlock().getType();
                ItemStack clickedi = new ItemStack(event.getClickedBlock().getType());
                if(player.getItemInHand().getType() == Material.AIR) {
                    player.setItemInHand(clickedi);
                    player.sendMessage("debug");
                }
               
                player.getItemInHand().setType(clicked);
               
                event.setCancelled(true);
               
            }
        }
     
  4. Offline

    xpyctum

    And on 12 line don't forget change:
    Code:
    player.getItemInHand().setType(clicked);
    
    to
    Code:
    player.setItemInHand(clicked);
    
     
  5. @xpyctum if you look reeeeeeeaaaaally closely, clicked is a Material and not an ItemStack
     
  6. Offline

    FloppehDeesk

    Java is pass by value, so when you call getItemInHand() for the player class it returns a COPY of the item in hand rather than giving you a direct reference to the object.
     
  7. No, really... how did you know that
     
  8. Offline

    FloppehDeesk

    chill dude, I was just adding onto it talking about object references and pass by value.
     
Thread Status:
Not open for further replies.

Share This Page