Solved How do i save clicked block's location and then load it?

Discussion in 'Spigot Plugin Development' started by Eprex1337, Feb 16, 2020.

Thread Status:
Not open for further replies.
  1. My code:
    Code (Java):
        @EventHandler
        public void onRightClick(PlayerInteractEvent e){
            if(e.getAction() == Action.RIGHT_CLICK_BLOCK) {
                if(e.getItem()!=null) {
                    if(e.getItem().hasItemMeta()) {
                        Player player = (Player) e.getPlayer();
                       
                        ItemStack item = e.getPlayer().getInventory().getItemInMainHand();
                        String itemName = item.getType().name().replaceAll("_"," ");
                        itemName = WordUtils.capitalizeFully(itemName);
                        if(item.hasItemMeta()) {
                        ItemMeta meta = item.getItemMeta();
                        if(meta.hasDisplayName()) {
                            itemName = meta.getDisplayName();
                            }
                        }
                        if(item.getType() == Material.BLAZE_ROD) {
                            if(itemName.equals("Center Tool")) {
                                e.setCancelled(true);
                 

                            }
                        }
                    }
                }
            }
    I would like to save clicked block's location and load it later. How can i do that?
     
  2. You could save them inside a file.
     
  3. drives_a_ford

    Moderator

    First of all, I'd recommend you check for PlayerInteractEvent#getHand before proceeding with the event. Otherwise your code can run twice like the javadocs suggest.

    Secondly, PlayerEvent#getPlayer (and thus PlayerInteractEvent#getPlayer) already returns a Player object, no need to cast it.

    Thirdly, I'd recommend caching the result of PlayerInteractEvent#getItem.

    Another issue is that you're first checking PlayerInteractEvent#getItem and then later checking the item in player's main hand. Do you really need both? I suspect you only need the one, so check for the hand (like I suggested to begin with) and stick to the #getItem result. Then you also don't need to check for meta existence twice.

    Another remark, identifying special items by simply their name is not a good idea. Anyone can come around and rename their blaze rod and have access to something they shouldn't.


    As for the question at hand, you can just Block#getLocation and then save it to a config with ConfigurationSection#set. At some point you'll want to FileConfiguration#save. And then at another time, you can simply ConfigurationSection#getLocation.
     
    • Winner Winner x 1
  4. I know I'll have to do this, but I'm new in plugin development, and i don't know how to. But anyway thanks for your help!
     
  5. Thanks! This helped me alot!
     
Thread Status:
Not open for further replies.