1.13.2 Problem with spawning entities with nbt

Discussion in 'Spigot Plugin Development' started by DrBnanaCraft, Jul 17, 2021.

  1. Hello, I'm trying to spawn a pig with nbt data, more precisely a pig with the CustomName "test", but I get a normal pig and an error message: net.minecraft.server.v1_13_R2.ReportedException: Loading entity NBT
    The error message points to the following line:nmsEntity.f(comp);

    here is my code:
    Code (Java):
    public static void setNBTTag(Entity entity, String key, NBTBase value) {
            net.minecraft.server.v1_13_R2.EntityLiving nmsEntity = (EntityLiving) ((CraftEntity)entity).getHandle();
           
            NBTTagCompound comp = new NBTTagCompound();
            nmsEntity.c(comp);
            comp.set(key, value);
            nmsEntity.f(comp);
        }
       
        public static void setNBTtag(Entity entity, String key, String value) {
            setNBTTag(entity, key, new NBTTagString(value));
        }
    Code (Java):
        @EventHandler
        public void onPlayerInteract(PlayerInteractEvent e) {
            Player p =e.getPlayer();
           
            try {
               
                if(p.getInventory().getItemInMainHand().getType() == Material.EGG) {
                    if(e.getClickedBlock().getType() == Material.COBBLESTONE) {
                        e.setCancelled(true);
                        Location loc = e.getClickedBlock().getLocation();
                       
                        loc.add(0, 1, 0);
                        try {
                            //Spawn the pig
                        Pig pig = (Pig) p.getWorld().spawnEntity(loc, EntityType.PIG);
                       
                        Bukkit.getScheduler().runTaskLater(Main.getPlugin(), new Runnable() {

                            @Override
                            public void run() {
                               
                                //run method to set nbt
                                EntityAPI.setNBTtag(pig, "CustomName", "test");
                               
                            }
                           
                        },1);
                       
                        }catch(Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
               
            }catch(Exception ex) {
               
            }
           
        }
    The scheduler was just a test, it doesn't work with or without a scheduler
     
  2. Might I ask why you are using NBT for this? You can change almost all NBT-related properties of mobs using the API, for example
    Code (Java):
    pig.setCustomName("test");
    pig.setCustomNameVisible(true);
     
  3. I know that, but I just wanted to understand how nbt works
     
  4. By the way, I found a way, I had to enter the CustomName as JSON. Now I'm looking for a way to save my own data in entities via nbt