Saving custom nbt to entities

Discussion in 'Spigot Plugin Development' started by teegah, Nov 4, 2016.

  1. Hey, I'm trying to save custom data to an entity, I was given these methods for reading nbt, writing and appending data however my data is not being saved. These are the methods
    Code (Text):
    private void write(Entity e, NBTTagCompound tag){
            net.minecraft.server.v1_10_R1.Entity handle = ((CraftEntity)e).getHandle();
            handle.f(tag);
        }

        private void append(Entity e, NBTTagCompound tag) {
            net.minecraft.server.v1_10_R1.Entity nmsEntity = ((CraftEntity)e).getHandle();

            NBTTagCompound oldTag = new NBTTagCompound();
            if (!nmsEntity.c(oldTag)) {
                nmsEntity.e(oldTag);
            }
            oldTag.a(tag);

            nmsEntity.f(tag);
        }

        private NBTTagCompound read(Entity e) {
            net.minecraft.server.v1_10_R1.Entity nmsEntity = ((CraftEntity)e).getHandle();

            NBTTagCompound tag = new NBTTagCompound();
            if (!nmsEntity.c(tag)) {
                nmsEntity.e(tag);
            }

            return tag;
        }
    and this is how I am attempting to save an integer to the nbt tag
    Code (Text):
    NBTTagCompound nbt = new NBTTagCompound();
                            int a = 2;
                            nbt.setInt("test",a);

                            append(p.getVehicle(),nbt);

                            Bukkit.broadcastMessage(""+ read(p.getVehicle()).getInt("test"));
    I end up getting 0 being broadcasted instead of 2. Any help would be greatly appreciated
     
  2. I had this same problem a few months ago, see here:
    https://www.spigotmc.org/threads/1-9-adding-custom-data-to-entities.128451/

    The problem appears to be that the load NBT method in Entity only certain pieces of data. Your best bet would either be using a HashMap to map an entity / entity uuid to an NBTTagCompound, but you'll have to be careful about entity despawning / spawning for resource cleanups - you don't want that map to full up with rubbish even when the entity has been killed or despawned etc.

    The other option is to extend CraftZombie, CraftSkeleton etc and override the methods. Make sure to call the super method and then write your data into a private NBTTagCompound variable.

    Edit: The reason it always returns 0, is that as I said the method does not write your custom data, so when you get it again the default value for a missing key is 0 because its an int.
     
  3. bump still looking for help, basically i want to tack on custom data to nbt tags of an entity, i know this can be 100% by overriding save/load methods in custom entity classes , but im trying to figure out how to add nbt data to default mobs