Solved SetCustomName and GetCustomName on a Chest

Discussion in 'Plugin Development' started by Piwik, Feb 1, 2019.

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

    Piwik

    Hi, I'm trying to edit the name of a chest using commands. However it seems to reset itself somehow, this code recreates what I've encoutered :
    Code:
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
       
       if(sender instanceof Player) {
         Player p = (Player) sender;
         if (cmd.getName().equalsIgnoreCase("a")){
           Block block = p.getTargetBlock((Set<Material>)null, 10);
           if (block.getState() instanceof Chest) {
             Chest chest = (Chest) block.getState();
             chest.setCustomName("konodioda");
             p.sendMessage(chest.getCustomName());
           }
           return true;
         }
         if (cmd.getName().equalsIgnoreCase("b")){
           Block block = p.getTargetBlock((Set<Material>)null, 10);
           if (block.getState() instanceof Chest) {
             Chest chest = (Chest) block.getState();
             p.sendMessage(chest.getCustomName());
           }
           return true;
         }
       }   
       return false;
    }
    As you can see, I make two commands : one that should find the chest in front of me, rename it and tell me the name it now has, and an other that should find the chest in front of me and tell me the name it has.
    Sounds simple, right ?

    Well, when I try to use the first then the second, the first command sends me the name I wanted to give the chest as expected, but when I use the second command right afterwards, I receive an empty string.

    This is even more obvious when you rename the chest manually with an anvil first.

    Both commands work the same way to find the chest and the first one seems to work so I don't think the problem comes from there, and it's the same for the conversion from Block to Chest.

    In my understanding, the CustomName should stay the same for the same chest, so either I'm not using it correctly or I do not understand what it does.

    (The point is to change the name that is displayed when opening the chest but also to be able to identify the chest)

    Thanks in advance for your help !
     
  2. Offline

    MightyOne

    First thing that came to my head is, that you often have to update a blockstate to apply the changes you made. But I don't know if that's the case with chests.
     
  3. Offline

    Piwik

    Yes, that was it, all I needed to do was add chest.update() and it now works.
    Thank you !
     
    MightyOne likes this.
  4. Offline

    Chr0mosom3

    @Piwik please mark this thread as solved.
     
Thread Status:
Not open for further replies.

Share This Page