gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:32:24 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com