TileEntity

Версия Minecraft
1.7.10
372
0
Есть блок с TileEntity, в нем храню одну переменную.
В GUI этого блока есть кнопка которая должна изменять эту переменную, при нажатие на кнопку с клиента посылаю пакет на сервер об этом изменение, а вот тайл через пакет не доходит, он там нулл.
 
7,099
324
1,510
В контейнере есть server-side метод enchantItem, вызываемый при клике по кнопке
 
7,099
324
1,510
А ты его передавай из iGuiHandler, и если он там null, то открывать инвентарь не нужно


Отправка своих пакетов - ну только ,если тебе это удобно. Майн сам ведь отправляет подобные пакеты, зачем городить свои?
 
372
0
разобрался, но единственная проблема которая осталось это, после обработки изменения переменой, я посылаю пакет о переоткрытие гуй, но когда он заново открывается то моя переменная там нулл


Код:
[17:49:18] [Server thread/ERROR] [FML]: SimpleChannelHandlerWrapper exception
java.lang.NullPointerException
at radic.test.containers.ContainerChest.<init>(ContainerChest.java:14) ~[ContainerChest.class:?]


Разобрался, после изменения вызвал tile.canUpdate();


Но, увы новая проблема, после переоткрытия GUI из за моей переменной в тайле и иза попытки к ней обратится, крашит

Код:
Caused by: java.lang.NullPointerException
 at radic.test.gui.GuiChest.drawGuiContainerBackgroundLayer(GuiChest.java:45) ~[GuiChest.class:?]
 at net.minecraft.client.gui.inventory.GuiContainer.drawScreen(GuiContainer.java:93) ~[GuiContainer.class:?]
 at net.minecraft.client.renderer.EntityRenderer.updateCameraAndRender(EntityRenderer.java:1137) ~[EntityRenderer.class:?]
 
372
0
Вот тайл
Код:
public class TileEntityChest extends TileEntity implements IInventory {
   private ItemStack[] inventory;
   public int inventoryLevel;
    private String customName;

    public TileEntityChest() {
        this.inventory = new ItemStack[this.getSizeInventory()];
        this.customName = "Inventory";
    }

    @Override
    public void readFromNBT(NBTTagCompound nbtTagCompound){
        super.readFromNBT(nbtTagCompound);

        NBTTagList tagList = nbtTagCompound.getTagList("Inventory", 10);
        for (int i = 0; i < tagList.tagCount(); i++){
            NBTTagCompound nbtTagCompound1 = (NBTTagCompound)tagList.getCompoundTagAt(i);
            byte slot = nbtTagCompound1.getByte("Slot");
            if(slot >= 0 && slot < inventory.length){
             inventory[slot] = ItemStack.loadItemStackFromNBT(nbtTagCompound1);
            }
        }

        inventoryLevel = nbtTagCompound.getInteger("inventoryLevel");
    }

    @Override
    public  void writeToNBT(NBTTagCompound nbtTagCompound){
        super.writeToNBT(nbtTagCompound);

        NBTTagList tagList = new NBTTagList();
        for(int i = 0; i < inventory.length; i++){
            ItemStack itemStack = inventory[i];
            if(itemStack != null){
                NBTTagCompound nbtTagCompound1 = new NBTTagCompound();
                nbtTagCompound1.setByte("Slot", (byte) i );
                itemStack.writeToNBT(nbtTagCompound1);
                tagList.appendTag(nbtTagCompound1);
            }
        }
        
        nbtTagCompound.setTag("Inventory", tagList);
        nbtTagCompound.setInteger("inventoryLevel", inventoryLevel);
    }
    
    public void clearInventory() {
      for (int i = 0; i < this.getSizeInventory(); i++) {
         this.inventory[i] = null;
      }
    }
    
   @Override
   public int getSizeInventory() {
      return 162;
   }

   @Override
   public ItemStack getStackInSlot(int index) {
      if (index < 0 || index >= this.getSizeInventory())
         return null;
      return this.inventory[index];
   }

   @Override
   public ItemStack decrStackSize(int index, int count) {
       if (this.getStackInSlot(index) != null) {
        ItemStack itemstack;

           if (this.getStackInSlot(index).stackSize <= count) {
               itemstack = this.getStackInSlot(index);
               this.setInventorySlotContents(index, null);
               this.markDirty();
               return itemstack;
           } else {
               itemstack = this.getStackInSlot(index).splitStack(count);

               if (this.getStackInSlot(index).stackSize <= 0) {
                this.setInventorySlotContents(index, null);
               } else {
                   this.setInventorySlotContents(index, this.getStackInSlot(index));
               }

               this.markDirty();
               return itemstack;
           }
       } else {
           return null;
       }
   }

   @Override
   public ItemStack getStackInSlotOnClosing(int index) {
       ItemStack stack = this.getStackInSlot(index);
       this.setInventorySlotContents(index, null);
       return stack;
 }

 @Override
 public void setInventorySlotContents(int index, ItemStack stack) {
    if (index < 0 || index >= this.getSizeInventory())
        return;

    if (stack != null && stack.stackSize > this.getInventoryStackLimit())
        stack.stackSize = this.getInventoryStackLimit();
        
    if (stack != null && stack.stackSize == 0)
        stack = null;

    this.inventory[index] = stack;
    this.markDirty();
 }

 @Override
 public String getInventoryName() { return this.customName; }

 @Override
 public boolean hasCustomInventoryName() { return true; }

 @Override
 public int getInventoryStackLimit() { return 64; }

 @Override
 public boolean isUseableByPlayer(EntityPlayer player) {
 return worldObj.getTileEntity(xCoord, yCoord, zCoord) == this && player.getDistanceSq(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5) < 64;
 }

 @Override
 public void closeInventory() {}

 @Override
 public boolean isItemValidForSlot(int p_94041_1_, ItemStack p_94041_2_) {
 return true;
 }
 
 @Override
 public Packet getDescriptionPacket() {
 NBTTagCompound tag = new NBTTagCompound();
 writeToNBT(tag);
 return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, tag);
 }
 
 @Override
 public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) {
 readFromNBT(pkt.func_148857_g());
 }

 @Override
 public void openInventory() {}
}


Вот контайнер
Код:
public class ContainerChest extends Container {
 private int z = 0;
 
 public ContainerChest(IInventory inventoryPlayer, TileEntityClanChest tile) {
 if (tile != null) z = tile.inventoryLevel;
 
 for (int y = 0; y < z; ++y) 
 for (int x = 0; x < 18; ++x) 
 this.addSlotToContainer(new Slot(tile, y * 18 + x, 8 + x * 18, 8 + y * 18));
 
        for (int y = 0; y < 3; ++y)
            for (int x = 0; x < 9; ++x) 
             this.addSlotToContainer(new Slot(inventoryPlayer, x + y * 9 + 9, 89 + x * 18, 174 + y * 18));
        
        for (int x = 0; x < 9; ++x)
            this.addSlotToContainer(new Slot(inventoryPlayer, x, 89 + x * 18, 232));
        
        this.detectAndSendChanges();
 }
 
 @Override
    public ItemStack transferStackInSlot(EntityPlayer playerIn, int fromSlot) {
        ItemStack previous = null;
        Slot slot = (Slot) this.inventorySlots.get(fromSlot);

        if (slot != null && slot.getHasStack()) {
            ItemStack current = slot.getStack();
            previous = current.copy();

            if (fromSlot < 18*z) {
                if (!this.mergeItemStack(current, 18*z, 18*z+36, true))
                    return null;
            } else {
                if (!this.mergeItemStack(current, 0, 18*z, false))
                    return null;
            }

            if (current.stackSize == 0)
                slot.putStack((ItemStack) null);
            else
                slot.onSlotChanged();

            if (current.stackSize == previous.stackSize)
                return null;
            slot.onPickupFromSlot(playerIn, current);
        }
        return previous;
    }
 
 @Override
    public boolean canInteractWith(EntityPlayer player) {
        return true;
    }
}


Вот гуй
Код:
public class GuiChest extends GuiContainer {
 private static final ResourceLocation texture = new ResourceLocation(Info.modid, "textures/gui/storage.png");
 private static final ResourceLocation extra = new ResourceLocation(Info.modid, "textures/gui/extraStorage.png");
 private static final ResourceLocation slots = new ResourceLocation(Info.modid, "textures/gui/slots.png");
 private static TileEntityChest tile;
 
 public GuiChest(IInventory playerInv, TileEntityChest tile) {
 super(new ContainerChest(playerInv, tile));
        this.ySize = 256;
        this.xSize = 338;
        this.tile = tile;
    }
 
    @Override
    protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
     GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
 mc.getTextureManager().bindTexture(texture);
 drawTexturedModalRect(guiLeft, guiTop, 0, 0, 169, ySize);
 mc.getTextureManager().bindTexture(extra);
 drawTexturedModalRect(guiLeft + 169, guiTop, 0, 0, 200, ySize);
 mc.getTextureManager().bindTexture(slots);
 
 GL11.glColor4f(1F, 0F, 0F, 1F);
 if (this.tile.inventoryLevel > 0) GL11.glColor4f(1F, 1F, 1F, 1F);
 drawTexturedModalRect(guiLeft + 7, guiTop + 7, 0, 0, 162, 18);
 drawTexturedModalRect(guiLeft + 169, guiTop + 7, 0, 0, 162, 18);
 
 GL11.glColor4f(1F, 0F, 0F, 1F);
 if (this.tile.inventoryLevel > 1) GL11.glColor4f(1F, 1F, 1F, 1F);
 drawTexturedModalRect(guiLeft + 7, guiTop + 25, 0, 0, 162, 18);
 drawTexturedModalRect(guiLeft + 169, guiTop + 25, 0, 0, 162, 18);
 
 GL11.glColor4f(1F, 0F, 0F, 1F);
 if (this.tile.inventoryLevel > 2) GL11.glColor4f(1F, 1F, 1F, 1F);
 drawTexturedModalRect(guiLeft + 7, guiTop + 43, 0, 0, 162, 18);
 drawTexturedModalRect(guiLeft + 169, guiTop + 43, 0, 0, 162, 18);
 
 GL11.glColor4f(1F, 0F, 0F, 1F);
 if (this.tile.inventoryLevel > 3) GL11.glColor4f(1F, 1F, 1F, 1F);
 drawTexturedModalRect(guiLeft + 7, guiTop + 61, 0, 0, 162, 18);
 drawTexturedModalRect(guiLeft + 169, guiTop + 61, 0, 0, 162, 18);
 
 GL11.glColor4f(1F, 0F, 0F, 1F);
 if (this.tile.inventoryLevel > 4) GL11.glColor4f(1F, 1F, 1F, 1F);
 drawTexturedModalRect(guiLeft + 7, guiTop + 79, 0, 0, 162, 18);
 drawTexturedModalRect(guiLeft + 169, guiTop + 79, 0, 0, 162, 18);
 
 GL11.glColor4f(1F, 0F, 0F, 1F);
 if (this.tile.inventoryLevel > 5) GL11.glColor4f(1F, 1F, 1F, 1F);
 drawTexturedModalRect(guiLeft + 7, guiTop + 97, 0, 0, 162, 18);
 drawTexturedModalRect(guiLeft + 169, guiTop + 97, 0, 0, 162, 18);
 
 GL11.glColor4f(1F, 0F, 0F, 1F);
 if (this.tile.inventoryLevel > 6) GL11.glColor4f(1F, 1F, 1F, 1F);
 drawTexturedModalRect(guiLeft + 7, guiTop + 115, 0, 0, 162, 18);
 drawTexturedModalRect(guiLeft + 169, guiTop + 115, 0, 0, 162, 18);
 
 GL11.glColor4f(1F, 0F, 0F, 1F);
 if (this.tile.inventoryLevel > 7) GL11.glColor4f(1F, 1F, 1F, 1F);
 drawTexturedModalRect(guiLeft + 7, guiTop + 133, 0, 0, 162, 18);
 drawTexturedModalRect(guiLeft + 169, guiTop + 133, 0, 0, 162, 18);
 
 GL11.glColor4f(1F, 0F, 0F, 1F);
 if (this.tile.inventoryLevel > 8) GL11.glColor4f(1F, 1F, 1F, 1F);
 drawTexturedModalRect(guiLeft + 7, guiTop + 151, 0, 0, 162, 18);
 drawTexturedModalRect(guiLeft + 169, guiTop + 151, 0, 0, 162, 18);
 
 this.buttonList.clear(); 
 if (this.tile.inventoryLevel < 9) { // ТА 
        this.buttonList.add(new GuiButton(0, guiLeft + 256, guiTop + 173, 73, 20, StatCollector.translateToLocal("gui.button.unlock.name")));
 }
    }
    
    @Override
 public void actionPerformed(GuiButton button) {
 switch(button.id) {
 case 0:
PacketDispatcher.sendToServer(new SyncChestLevelMessage(tile.xCoord, tile.yCoord, tile.zCoord, 1));
 this.onGuiClosed();
 PacketDispatcher.sendToServer(new OpenGuiMessage(Test.GUI_CHEST_INV));
 }
 break;
 }
 }
}
 
7,099
324
1,510
Ты нигде не присваиваешь значение переменной inventoryLevel,кроме чтения из nbt, но в него все равно записывается null
 
372
0
hohserg написал(а):
Ты нигде не присваиваешь значение переменной inventoryLevel,кроме чтения из nbt, но в него все равно записывается null

Для этого у меня пакет

Код:
public class SyncChestLevelMessage extends AbstractServerMessage<SyncChestLevelMessage> {
 private int level;
 private int x, y, z;
 
 public SyncChestLevelMessage() {}
 
 public SyncChestLevelMessage(int x, int y, int z, int level) {
 this.level = level;
 this.x = x;
 this.y = y;
 this.z = z;
 }

 @Override
 protected void read(PacketBuffer buffer) {
 level = buffer.readInt();
 x = buffer.readInt();
 y = buffer.readInt();
 z = buffer.readInt();
 }

 @Override
 protected void write(PacketBuffer buffer) {
 buffer.writeInt(level);
 buffer.writeInt(x);
 buffer.writeInt(y);
 buffer.writeInt(z);
 }

 @Override
 public void process(EntityPlayer player, Side side) {
 TileEntityChest tile = (TileEntityChest) FMLCommonHandler.instance().getMinecraftServerInstance().getEntityWorld().getTileEntity(x, y, z);
 tile.inventoryLevel += level;
 if (tile.inventoryLevel > 9) tile.inventoryLevel = 9;
 tile.canUpdate();
}
}
 
Сверху