Get a horse's inventory contents and save them to a config

Discussion in 'Plugin Development' started by MrDplugins, Nov 2, 2017.

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

    MrDplugins

    How would I go about getting the contents of a horses inventory? I want to save a players horse, its inventory contents to a config and then later recall that information when spawning a horse and set its inventory contents to the previously saved data.

    What I have so far.

    Code:
     
    for (World world : Bukkit.getServer().getWorlds()) {
          for (Entity entity : world.getEntities())
                {
                    if(entity == typehorse)
                        // get horse data and save it to config
    
    
    
     
  2. Offline

    Zombie_Striker

    @MrDplugins
    1. If the entity is an instance of Horse, cast it and get its inventory.
    2. If the entity is not a horse, but a mule, skeleton horse, donkey, ect., then you will need to cast it to an AbstractHorse, and use getEquipment to get the items on that horse.
     
  3. Offline

    ipodtouch0218

    Why would you need to check specifically what type of Horse it is? AbstractHorse itself contains the getInventory() method.
     
  4. Offline

    Unknown123

    @MrDplugins well, This is untested but should work. The code isn't the best. And you will need to create a seperate file per inventory. So there might be 1000 better ways to do this, just my first attempt.
    Code:
        private static void store(Inventory inv, File file) throws FileNotFoundException, IOException {
            try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
                oos.writeInt(inv.getSize());
                for (ItemStack item : inv) {
                    oos.writeObject(item.serialize());
                }
            }
        }
    
        private static ItemStack[] read(File file) throws FileNotFoundException, IOException, ClassNotFoundException {
            try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
                ItemStack[] items = new ItemStack[ois.readInt()];
                for (int i = 0; i < items.length; i++) {
                    items[i] = (ItemStack) ois.readObject();
                }
                return items;
            }
        }
     
Thread Status:
Not open for further replies.

Share This Page