java - 如何反序列化玩家的库存?

标签 java minecraft bukkit

这是我的序列化方法。稍后我将如何反序列化/加载它?

invs 是我的 inventories.yml FileConfiguration 变量。

public void action(Player p){
    PlayerInventory i = p.getInventory();
    int slot = 0;
    for(ItemStack item : i){
        Map<String, Object> itemS = item.serialize();
        if(Main.invs.get(p.getName() + ".inventory.slot." + slot) == null){
            Main.invs.createSection(p.getName()+ ".inventory.slot." + slot);
        }
        Main.invs.set(p.getName() + ".inventory.slot." + slot, itemS);
        slot = slot + 1;
    }
    slot = 0;
}

最佳答案

试试这个:

public PlayerInventory deserializeInventory(Player p) {
    PlayerInventory inv = p.getInventory();
    for(int slot = 0; slot < 36 /*Size of inventory */; slot++){
        //Removes any existing item from the inventory.
        inv.clear(slot);

        Object itemTemp = Main.invs.get(p.getName() + ".inventory.slot." + slot);
        if (itemTemp == null) { //Skip null values.
            continue;
        }
        if (!(itemTemp instanceof ItemStack)) {
            //Might want to do an error message, but for now just ignore this.
            continue;
        }
        ItemStack item = (ItemStack) itemTemp;
        inv.setItem(slot, item);
    }
    return inv;
}

作为旁注,我强烈建议将您的序列化方法更改为:

public void action(Player p){
    PlayerInventory i = p.getInventory();
    for(int slot = 0; slot < 36 /*Size of inventory */; slot++){
        ItemStack item = i.getItem(slot);
        if (item == null || item.getType() == Material.AIR) { //Do nothing.
            continue;
        }
        Map<String, Object> itemS = item.serialize();
        if(Main.invs.get(p.getName() + ".inventory.slot." + slot) == null){
            Main.invs.createSection(p.getName()+ ".inventory.slot." + slot);
        }
        Main.invs.set(p.getName() + ".inventory.slot." + slot, itemS);
    }
}

这样做将保留项目的位置,并添加一些错误检查功能。

关于java - 如何反序列化玩家的库存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25838757/

相关文章:

java - XSSFRichTextString 中忽略新行

java - 防止伪造客户端数据Java?

java - Minecraft fontRenderer.drawString() 立即消失

java - 通过 OSHI API 从传感器检索信息时为什么会发生这种情况?

java - 如何在 Spigot 1.9 中播放 Minecraft 声音并使其在同一位置播放

java - 启动并获取 .jar 的输出(例如 Minecraft Bukkit .jar)

java - 构造对象时初始化实例变量的两种方式?

Java : Is there a way to automatically cast a return value?

java - 为什么?在java中使用接口(interface)编码的最佳方法?

java - Bukkit java 插件中的 ClassNotFoundException