Jump to content

Recommended Posts

Posted (edited)

I was making a tile entity that stores stuff, and when I was done I got this weird NullPointerException I can't figure out how to solve!

My code of the Tile Entity:

package beta.mod.tileentity.barrel;

import beta.mod.init.BlockInit;
import beta.mod.tileentity.ModTET;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.IChestLid;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityLockableLoot;
import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.NonNullList;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.IBlockReader;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.LazyOptional;

public class TileEntityBarrel extends TileEntityLockableLoot implements IChestLid, ITickable {
	private NonNullList<ItemStack> items = NonNullList.withSize(9, ItemStack.EMPTY);
	protected float lidAngle, prevLidAngle;
	protected int numPlayersUsing;
	private int ticksSinceSync;
	private net.minecraftforge.common.util.LazyOptional<net.minecraftforge.items.IItemHandler> handler;
	
	protected TileEntityBarrel(TileEntityType<?> type) {
		super(type);
	}
	
	public TileEntityBarrel() {
		this(ModTET.BARREL);
	}
	
	@Override
	public int getSizeInventory() {
		return 9;
	}
	
	@Override
	public boolean isEmpty() {
		for(ItemStack stack : this.items) {
			if(!stack.isEmpty()) {
				return false;
			}
		}
		
		return true;
	}
	
	@Override
	public ITextComponent getName() {
		ITextComponent component = this.getCustomName();
		return (ITextComponent)(component != null ? component : new TextComponentTranslation("container.barrel"));
	}
	
	@Override
	public void read(NBTTagCompound compound) {
		super.read(compound);
		this.items = NonNullList.withSize(this.getSizeInventory(), ItemStack.EMPTY);
		if(!this.checkLootAndRead(compound)) {
			ItemStackHelper.loadAllItems(compound, items);
		}
		
		if(compound.contains("CustomName", 8)) {
			this.customName = ITextComponent.Serializer.fromJson(compound.getString("CustomName"));
		}
	}
	
	@Override
	public NBTTagCompound write(NBTTagCompound compound) {
		super.write(compound);
		if(!this.checkLootAndWrite(compound)) {
			ItemStackHelper.saveAllItems(compound, items);
		}
		
		ITextComponent component = this.getCustomName();
		if(component != null) {
			compound.setString("CustomName", ITextComponent.Serializer.toJson(component));
		}
		
		return compound;
	}
	
	@Override
	public int getInventoryStackLimit() {
		return 64;
	}
	
	@Override
	public void tick() {
		int i = this.pos.getX();
		int j = this.pos.getY();
		int k = this.pos.getZ();
		this.ticksSinceSync++;
		if(!this.world.isRemote && this.numPlayersUsing != 0 && (this.ticksSinceSync + i + j + k) % 200 == 0) {
			this.numPlayersUsing = 0;
			
			for(EntityPlayer entityplayer : this.world.getEntitiesWithinAABB(EntityPlayer.class, new AxisAlignedBB((double)((float)i - 5.0F), (double)((float)j - 5.0F), (double)((float)k - 5.0F), (double)((float)(i + 1) + 5.0F), (double)((float)(j + 1) + 5.0F), (double)((float)(k + 1) + 5.0F)))) {
				if(entityplayer.openContainer instanceof ContainerBarrel) {
					this.numPlayersUsing++;
				}
			}
		}
		
		this.prevLidAngle = this.lidAngle;
		if(this.numPlayersUsing > 0 && this.lidAngle == 0) {
			this.playSound(SoundEvents.BLOCK_IRON_TRAPDOOR_OPEN);
		}
		
		if(this.numPlayersUsing == 0 && this.lidAngle > 0.0f || this.numPlayersUsing > 0 && this.lidAngle < 1.0f) {
			float f2 = this.lidAngle;
	         if (this.numPlayersUsing > 0) {
	            this.lidAngle += 0.1F;
	         } else {
	            this.lidAngle -= 0.1F;
	         }

	         if (this.lidAngle > 1.0F) {
	            this.lidAngle = 1.0F;
	         }
	         
	         if(this.lidAngle < 0.5f && f2 >= 0.5f) {
	        	 this.playSound(SoundEvents.BLOCK_IRON_TRAPDOOR_CLOSE);
	         }
	         
	         if(this.lidAngle < 0.0f) {
	        	 this.lidAngle = 0.0f;
	         }
		}
	}
	
	private void playSound(SoundEvent soundIn) {
		double d0 = (double)this.pos.getX() + 0.5d;
		double d1 = (double)this.pos.getY() + 0.5d;
		double d2 = (double)this.pos.getZ() + 0.5d;
		
		this.world.playSound(null, d0, d1, d2, soundIn, SoundCategory.BLOCKS, 0.5f, this.world.rand.nextFloat() * 0.1f + 0.9f);
	}
	
	@Override
	public boolean receiveClientEvent(int id, int type) {
		if(id == 1) {
			this.numPlayersUsing = type;
			return true;
		} else {
			return super.receiveClientEvent(id, type);
		}
	}
	
	@Override
	public void openInventory(EntityPlayer player) {
		if(!player.isSpectator()) {
			if(this.numPlayersUsing < 0) {
				this.numPlayersUsing = 0;
			}
			
			this.numPlayersUsing++;
			this.onOpenOrClose();
		}
	}
	
	@Override
	public void closeInventory(EntityPlayer player) {
		if(!player.isSpectator()) {
			this.numPlayersUsing--;
			this.onOpenOrClose();
		}
	}
	
	protected void onOpenOrClose() {
		Block block = this.getBlockState().getBlock();
		if(block instanceof BlockBarrel) {
			this.world.addBlockEvent(this.pos, block, 1, this.numPlayersUsing);
			this.world.notifyNeighborsOfStateChange(this.pos, block);
		}
	}
	
	@Override
	public String getGuiID() {
		return "moresimplestuff:barrel";
	}
	
	@Override
	public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn) {
		this.fillWithLoot(playerIn);
		return new ContainerBarrel(playerInventory, this, playerIn);
	}
	
	@Override
	protected NonNullList<ItemStack> getItems() {
		return this.items;
	}
	
	@Override
	protected void setItems(NonNullList<ItemStack> itemsIn) {
		this.items = itemsIn;
	}
	
	@Override
	public float getLidAngle(float partialTicks) {
		return this.prevLidAngle + (this.lidAngle - this.prevLidAngle) * partialTicks;
	}
	
	public static int getPlayersUsing(IBlockReader reader, BlockPos posIn) {
		IBlockState state = reader.getBlockState(posIn);
		if(state.hasTileEntity()) {
			TileEntity te = reader.getTileEntity(posIn);
			if(te instanceof TileEntityBarrel) {
				return ((TileEntityBarrel)te).numPlayersUsing;
			}
		}
		
		return 0;
	}
	
	public static void swapContents(TileEntityBarrel barrel, TileEntityBarrel otherBarrel) {
		NonNullList<ItemStack> list = barrel.getItems();
		barrel.setItems(otherBarrel.getItems());
		otherBarrel.setItems(list);
	}
	
	@Override
	public void updateContainingBlockInfo() {
		super.updateContainingBlockInfo();
		if(this.handler != null) {
			this.handler.invalidate();
			this.handler = null;
		}
	}
	
	@Override
	public <T> LazyOptional<T> getCapability(Capability<T> cap, EnumFacing side) {
		if(!this.removed && cap == net.minecraftforge.items.CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
			if(this.handler == null) {
				this.handler = LazyOptional.of(this::createUnSidedHandler);
			}
			return this.handler.cast();
		}
		return super.getCapability(cap, side);
	}
	
	@Override
	public void remove() {
		super.remove();
		if(handler != null) {
			handler.invalidate();
		}
	}
}

Error log:

[23:53:40.268] [Server thread/FATAL] [minecraft/MinecraftServer]: Error executing task
java.util.concurrent.ExecutionException: java.lang.NullPointerException
	at java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[?:1.8.0_202]
	at java.util.concurrent.FutureTask.get(FutureTask.java:192) ~[?:1.8.0_202]
	at net.minecraft.util.Util.runTask(Util.java:127) [?:?]
	at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:770) [?:?]
	at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:724) [?:?]
	at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:122) [?:?]
	at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:611) [?:?]
	at java.lang.Thread.run(Thread.java:748) [?:1.8.0_202]
Caused by: java.lang.NullPointerException
	at net.minecraft.tileentity.TileEntity.getBlockState(TileEntity.java:145) ~[?:?]
	at beta.mod.tileentity.barrel.TileEntityBarrel.onOpenOrClose(TileEntityBarrel.java:183) ~[?:?]
	at beta.mod.tileentity.barrel.TileEntityBarrel.openInventory(TileEntityBarrel.java:170) ~[?:?]
	at beta.mod.tileentity.barrel.ContainerBarrel.<init>(ContainerBarrel.java:16) ~[?:?]
	at beta.mod.tileentity.barrel.TileEntityBarrel.createContainer(TileEntityBarrel.java:198) ~[?:?]
	at net.minecraftforge.fml.network.NetworkHooks.openGui(NetworkHooks.java:171) ~[?:?]
	at net.minecraftforge.fml.network.NetworkHooks.openGui(NetworkHooks.java:114) ~[?:?]
	at beta.mod.tileentity.barrel.BlockBarrel.onBlockActivated(BlockBarrel.java:55) ~[?:?]
	at net.minecraft.block.state.IBlockState.onBlockActivated(IBlockState.java:315) ~[?:?]
	at net.minecraft.server.management.PlayerInteractionManager.processRightClickBlock(PlayerInteractionManager.java:389) ~[?:?]
	at net.minecraft.network.NetHandlerPlayServer.processTryUseItemOnBlock(NetHandlerPlayServer.java:873) ~[?:?]
	at net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock.processPacket(CPacketPlayerTryUseItemOnBlock.java:62) ~[?:?]
	at net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock.processPacket(CPacketPlayerTryUseItemOnBlock.java:13) ~[?:?]
	at net.minecraft.network.PacketThreadUtil.lambda$checkThreadAndEnqueue$0(PacketThreadUtil.java:15) ~[?:?]
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[?:1.8.0_202]
	at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[?:1.8.0_202]
	at net.minecraft.util.Util.runTask(Util.java:126) ~[?:?]
	... 5 more

(Most of the code is from the chest class)

Edited by MyRedAlien43
Wrong title
Posted

The only thing being null at that point is the world of the TE. Use the debugger to figure out why it is null.

 

Also your TE's code is an insane mess.

57 minutes ago, MyRedAlien43 said:

private NonNullList<ItemStack> items = NonNullList.withSize(9, ItemStack.EMPTY);

Don't do this, use forge's provided capabilities, like ItemStackHandler.

 

59 minutes ago, MyRedAlien43 said:

extends TileEntityLockableLoot

Don't. This makes you do the unnecesarry IInventory implementation. Just use capabilities.

 

1 hour ago, MyRedAlien43 said:

public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn) {

Don't do any of this. Just do this in your gui handler.

 

 

Posted (edited)
15 hours ago, V0idWa1k3r said:

The only thing being null at that point is the world of the TE. Use the debugger to figure out why it is null.

 

Also your TE's code is an insane mess.

Don't do this, use forge's provided capabilities, like ItemStackHandler.

 

Don't. This makes you do the unnecesarry IInventory implementation. Just use capabilities.

 

 

I got the gui and the container in the gui handler, but could u show an example of how i should set it up?

Or, to be more exact, use ItemStackHandler as a capability?

Edited by MyRedAlien43
Posted
40 minutes ago, MyRedAlien43 said:

Or, to be more exact, use ItemStackHandler as a capability?

Just ditch all of those things and simply interact with an ItemStackHandler as your inventory. That's it.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • I have no idea what the flip is going on, I can load the modpack just fine at forge 42.2.0 but any forge version above it insta-crashes with exit code 1. Can somebody tell me what's going on, this is minecraft 1.20.1 Latest.log: https://pastebin.com/pBUL1ZFa
    • does anyone know how to incorporate custom noise settings into a custom dimension through the use of datagen, I have created a custon json file for the noise settings that I want but I just don't know how to get it to register with the generated json file of the custom dimension.   here is the code for the dimension class package net.hurst.lustria.worldgen.dimension; import com.mojang.datafixers.util.Pair; import net.hurst.lustria.Lustria; import net.hurst.lustria.worldgen.biome.ModBiomes; import net.hurst.lustria.worldgen.registries.LustriaNoiseSettings; import net.minecraft.core.HolderGetter; import net.minecraft.core.registries.Registries; import net.minecraft.data.worldgen.BootstapContext; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.util.valueproviders.ConstantInt; import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.*; import net.minecraft.world.level.dimension.BuiltinDimensionTypes; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.dimension.LevelStem; import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; import java.util.List; import java.util.OptionalLong; public class ModDimensions { public static final ResourceKey<LevelStem> LUSTRIA_KEY = ResourceKey.create(Registries.LEVEL_STEM, ResourceLocation.fromNamespaceAndPath(Lustria.MOD_ID, "lustriadim")); public static final ResourceKey<Level> LUSTRIA_LEVEL_KEY = ResourceKey.create(Registries.DIMENSION, ResourceLocation.fromNamespaceAndPath(Lustria.MOD_ID, "lustriadim")); public static final ResourceKey<DimensionType> LUSTRIA_DIM_TYPE = ResourceKey.create(Registries.DIMENSION_TYPE, ResourceLocation.fromNamespaceAndPath(Lustria.MOD_ID, "lustriadim_type")); public static void bootstrapType(BootstapContext<DimensionType> context) { context.register(LUSTRIA_DIM_TYPE, new DimensionType( OptionalLong.of(12000), // fixedTime false, // hasSkylight true, // hasCeiling false, // ultraWarm false, // natural 1.0, // coordinateScale true, // bedWorks false, // respawnAnchorWorks -64, // minY 256, // height 256, // logicalHeight BlockTags.INFINIBURN_OVERWORLD, // infiniburn BuiltinDimensionTypes.OVERWORLD_EFFECTS, // effectsLocation 0.0f, // ambientLight new DimensionType.MonsterSettings(false, false, ConstantInt.of(0), 0))); } public static void bootstrapStem(BootstapContext<LevelStem> context) { HolderGetter<Biome> biomeRegistry = context.lookup(Registries.BIOME); HolderGetter<DimensionType> dimTypes = context.lookup(Registries.DIMENSION_TYPE); HolderGetter<NoiseGeneratorSettings> noiseGenSettings = context.lookup(Registries.NOISE_SETTINGS); NoiseBasedChunkGenerator wrappedChunkGenerator = new NoiseBasedChunkGenerator( new FixedBiomeSource(biomeRegistry.getOrThrow(Biomes.BEACH)), noiseGenSettings.getOrThrow(NoiseGeneratorSettings.CAVES)); NoiseBasedChunkGenerator noiseBasedChunkGenerator = new NoiseBasedChunkGenerator( MultiNoiseBiomeSource.createFromList( new Climate.ParameterList<>(List.of(Pair.of( Climate.parameters(0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F), biomeRegistry.getOrThrow(Biomes.BEACH)), Pair.of( Climate.parameters(0.1F, 0.2F, 0.0F, 0.2F, 0.0F, 0.0F, 0.0F), biomeRegistry.getOrThrow(Biomes.BIRCH_FOREST)), Pair.of( Climate.parameters(0.3F, 0.6F, 0.1F, 0.1F, 0.0F, 0.0F, 0.0F), biomeRegistry.getOrThrow(Biomes.OCEAN)), Pair.of( Climate.parameters(0.4F, 0.3F, 0.2F, 0.1F, 0.0F, 0.0F, 0.0F), biomeRegistry.getOrThrow(Biomes.DARK_FOREST)) ))), noiseGenSettings.getOrThrow(NoiseGeneratorSettings.CAVES)); LevelStem stem = new LevelStem(dimTypes.getOrThrow(ModDimensions.LUSTRIA_DIM_TYPE), noiseBasedChunkGenerator); context.register(LUSTRIA_KEY, stem); } } minecraft version is 1.20.1
    • Please read the FAQ (https://forums.minecraftforge.net/topic/125488-rules-and-frequently-asked-questions-faq/) and post logs as described there using a site like https://mclo.gs and post the link to it here. It may have the information required to solve your problem.  
    • the error code comes up when i trry to run it and ive tried to fix it but i cant  
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.