Jump to content

Recommended Posts

Posted

Why i need this: My block entity is a teleporter, you put an item with coordinates inside the gui and when you shift above the block it teleports you, the problem is that if both block entities are too far away one from another is crashes the game 

java.lang.NullPointerException: Cannot read field "itemHandler" because the return value of "net.minecraft.world.level.Level.getBlockEntity(net.minecraft.core.BlockPos)" is null

im pretty shure it needs the chunk loaded because it teleports me instantly and it doesnt have time to load the things of the block entity

 

My point is that in the tick method, im trying to force the chunk just like the player's spawnpoint does, but is throwing me this error:

Caused by: java.lang.NullPointerException: Cannot invoke "net.minecraft.server.MinecraftServer.getLevel(net.minecraft.resources.ResourceKey)" because the return value of "net.minecraft.world.level.Level.getServer()" is null
public static void tick(Level level, BlockPos pPos, BlockState pState, TeleportBlockEntity blockEntity) {
  	ChunkPos chunkPos = new ChunkPos(pPos);
        ResourceKey<Level> currentDimension = level.dimension();
        ServerLevel serverLevel = level.getServer().getLevel(currentDimension);
        ForgeChunkManager.forceChunk(serverLevel, Constants.MOD_ID, pPos, chunkPos.x,chunkPos.z,true,true);
}

 

Posted

What/where is that tick() method?

You are just showing some random code without any context.

 

From the error message it looks like it is getting called on the client, since Level.getServer() is returning null.

 

I would guess your other error (for which you don't even grace us with code) has the same problem.

Forcing chunk loading is not necessary to solve your problem.

Your problem is you can't reference chunks outside the render distance on the client. You shouldn't be doing this processing there.

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

Posted (edited)
28 minutes ago, warjort said:

What/where is that tick() method?

You are just showing some random code without any context.

 

From the error message it looks like it is getting called on the client, since Level.getServer() is returning null.

 

I would guess your other error (for which you don't even grace us with code) has the same problem.

Forcing chunk loading is not necessary to solve your problem.

Your problem is you can't reference chunks outside the render distance on the client. You shouldn't be doing this processing there.

the chunk loading problem is solved but i realized that this is not necessary, actually is useless

// I had to add this if lol
if(!level.isClientSide) {
            ChunkPos chunkPos = new ChunkPos(pPos);
            ResourceKey<Level> currentDimension = level.dimension();
            ServerLevel serverLevel = (ServerLevel)level.getServer().getLevel(currentDimension);
            ForgeChunkManager.forceChunk(serverLevel, Constants.MOD_ID, pPos, chunkPos.x,chunkPos.z,true,true);
}

but actually as you said, forcing the chunks is not helping me, im back to problem 1

Caused by: java.lang.NullPointerException: Cannot read field "itemHandler" because the return value of "net.minecraft.world.level.Level.getBlockEntity(net.minecraft.core.BlockPos)" is null

what can i do

Edited by ElTotisPro50
Posted
23 minutes ago, ElTotisPro50 said:

but actually as you said, forcing the chunks is not helping me, im back to problem 1

a little of topic, there is really, really no need to do it 20 times each second.

Posted
Quote

what can i do

You can start by making your question answerable. A one line NPE completely out of context is useless.

You don't even show the stacktrace - it needs more than that.

I wonder if you even know where in your code this error happens?

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

Posted
5 minutes ago, warjort said:

I wonder if you even know where in your code this error happens?

If im correct, here (in the tick method): "ItemStack stack0 = ((TeleporterBlockEntity) level.getBlockEntity(pPos)).itemHandler.getStackInSlot(0);"

The weird thing is that minecraft only crashes sometimes and when it wants, for example if i have 2 teleports 500 blocks away from each and i use one of them minecraft crashes, or when i tp too far away, but that only crashes the game sometimes, is VERY WEIRD

 

BTW in the crash report the error is in line 219, this is line 219:

ItemStack stack0 = ((TeleporterBlockEntity) level.getBlockEntity(pPos)).itemHandler.getStackInSlot(0);

Crash report: https://pastebin.com/s2KqP6yX

Block entity Class:

public class TeleporterBlockEntity extends BlockEntity implements MenuProvider {

    private final ContainerData data;
	public final ItemStackHandler itemHandler = new ItemStackHandler(Constants.TELEPORTER_TOTALSLOTS) {
		@Override
		protected void onContentsChanged(int slot) {
            setChanged();
        };
};

    @Override
    public void setChanged() {
        super.setChanged();
    }

	private LazyOptional<IItemHandler> lazyItemHandler = LazyOptional.empty();

	public TeleporterBlockEntity(BlockPos pos, BlockState state) {
		super(ModBlockEntities.TELEPORTER_BLOCKENTITY.get(), pos, state);
	}

    @Override
	public AbstractContainerMenu createMenu(int id, Inventory inv, Player player) {
		return new TeleporterMenu(id, inv, this, this.data);
	}

	@Override
	public Component getDisplayName() {
		return new TextComponent("");
	}
	
	@Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @javax.annotation.Nullable Direction side) {
        if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
            return lazyItemHandler.cast();
        }
        return super.getCapability(cap, side);
    }

    @Override
    public void onLoad() {
        super.onLoad();
        lazyItemHandler = LazyOptional.of(() -> itemHandler);
        ModMessages.sendToClients(new PacketSyncTeleporterPosToClient(posX,posY,posZ,dimName,worldPosition));
    }

    @Override
    public void invalidateCaps()  {
        super.invalidateCaps();
        lazyItemHandler.invalidate();
    }

    @Override
    protected void saveAdditional(@NotNull CompoundTag tag) {
        tag.put("inventory", itemHandler.serializeNBT());
        super.saveAdditional(tag);
    }
    @Override
    public void load(CompoundTag tag) {
        super.load(tag);
        itemHandler.deserializeNBT(tag.getCompound("inventory"));
    }

    public void drops() {
        SimpleContainer inventory = new SimpleContainer(itemHandler.getSlots());
        for (int i = 0; i < itemHandler.getSlots(); i++) {
            inventory.setItem(i, itemHandler.getStackInSlot(i));
        }
        Containers.dropContents(this.level, this.worldPosition, inventory);
    }

    public boolean hasCrystal() {
        return this.getItemFromSlot(0).getItem() == ModItems.TELEPORTCRYSTAL.get();
    }
    public void setItemToSlot(int slot, ItemStack stack) {
        stack.setCount(1);
        this.itemHandler.setStackInSlot(slot, stack);
    }
    public ItemStack getItemFromSlot(int slot) { return this.itemHandler.getStackInSlot(slot); }

    public static void tick(Level level, BlockPos pPos, BlockState pState, TeleporterBlockEntity blockEntity) {
        level.getEntitiesOfClass(Player.class, new AABB(pPos.getX(), pPos.getY(), pPos.getZ(), pPos.getX() + 1, pPos.getY() + 1, pPos.getZ() + 1)).forEach(entity -> {
            if(!(entity instanceof Player)) return;
            if(!entity.isShiftKeyDown() || !entity.isCrouching()) return;
            if(level.getBlockEntity(pPos) != null && level.getBlockEntity(pPos) instanceof TeleporterBlockEntity) {
                ItemStack stack = ((TeleporterBlockEntity) level.getBlockEntity(pPos)).itemHandler.getStackInSlot(0);
                CompoundTag tag = stack.getTag();
                if(tag == null) return;
                entity.playSound(SoundEvents.ENDERMAN_TELEPORT, 1, 1);
                if(!level.isClientSide) {
                    String dim = TotisPlayerUtils.getDimension(stack);
                    ResourceKey<Level> currentDim = level.dimension();
                    ServerLevel serverWorld = ((ServerLevel)level).getServer().getLevel(currentDim);
                    ServerPlayer player = (ServerPlayer)entity;
                    ResourceKey<Level> storedKey = ResourceKey.create(Registry.DIMENSION_REGISTRY, new ResourceLocation(dim));
                    ServerLevel storedWorld = ((ServerLevel)level).getServer().getLevel(storedKey);
                    if(serverWorld == storedWorld) {
                        player.teleportTo(tag.getInt("x")+0.5,tag.getInt("y")+1,tag.getInt("z")+0.5);
                    } else {
                        player.teleportTo(storedWorld, tag.getInt("x")+0.5,tag.getInt("y")+1,tag.getInt("z")+0.5, player.getRespawnAngle(), player.getRespawnAngle());
                    }
                }
                entity.playSound(SoundEvents.ENDERMAN_TELEPORT, 1, 1);
            }
        });
    }


    /*Synchronization to the client*/
    @Nullable
    @Override
    public Packet<ClientGamePacketListener> getUpdatePacket() {
        return ClientboundBlockEntityDataPacket.create(this);
    }
    @Override
    public CompoundTag getUpdateTag() {
        CompoundTag tag = saveWithoutMetadata();
        load(tag);
        return tag;
    }
    @Override
    public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) {
        super.onDataPacket(net, pkt);
        load(pkt.getTag());
    }
    @Override
    public void handleUpdateTag(CompoundTag tag) {
        super.handleUpdateTag(tag);
    }
}

 

Posted
    public static void tick(Level level, BlockPos pPos, BlockState pState, TeleporterBlockEntity blockEntity) {

-- snip --

            if(level.getBlockEntity(pPos) != null && level.getBlockEntity(pPos) instanceof TeleporterBlockEntity) {
                ItemStack stack = ((TeleporterBlockEntity) level.getBlockEntity(pPos)).itemHandler.getStackInSlot(0);

Why are you doing all this extra work? You are told the TeleporterBlockEntity as a parameter to this method.

 

You still have this "broken" code, which I told you about on your previous thread but you obviously didn't fix it.

    @Override
    public CompoundTag getUpdateTag() {
        CompoundTag tag = saveWithoutMetadata();

        // Why are you loading during the save?
        load(tag);
        return tag;
    }
    @Override
    public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) {
        super.onDataPacket(net, pkt); // This calls load()
        load(pkt.getTag()); // so this is duplicate work - in fact the whole onDataPacket() method is redundant, you can remove it and use the default implementation
    }

    // This is redundant too, overriding a method and just calling super is pointless
    @Override
    public void handleUpdateTag(CompoundTag tag) {
        super.handleUpdateTag(tag);
    }

 

When you've fixed your block entity load/save code and are sure it is working properly, either;

* create a new test world

* break all your BlockEntity blocks and replace them

that way you will know there aren't blocks lying around with broken nbt data from your previous buggy code

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

Posted
7 minutes ago, warjort said:
    public static void tick(Level level, BlockPos pPos, BlockState pState, TeleporterBlockEntity blockEntity) {

-- snip --

            if(level.getBlockEntity(pPos) != null && level.getBlockEntity(pPos) instanceof TeleporterBlockEntity) {
                ItemStack stack = ((TeleporterBlockEntity) level.getBlockEntity(pPos)).itemHandler.getStackInSlot(0);

Why are you doing all this extra work? You are told the TeleporterBlockEntity as a parameter to this method.

 

You still have this "broken" code, which I told you about on your previous thread but you obviously didn't fix it.

    @Override
    public CompoundTag getUpdateTag() {
        CompoundTag tag = saveWithoutMetadata();

        // Why are you loading during the save?
        load(tag);
        return tag;
    }
    @Override
    public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) {
        super.onDataPacket(net, pkt); // This calls load()
        load(pkt.getTag()); // so this is duplicate work - in fact the whole onDataPacket() method is redundant, you can remove it and use the default implementation
    }

    // This is redundant too, overriding a method and just calling super is pointless
    @Override
    public void handleUpdateTag(CompoundTag tag) {
        super.handleUpdateTag(tag);
    }

 

When you've fixed your block entity load/save code and are sure it is working properly, either;

* create a new test world

* break all your BlockEntity blocks and replace them

that way you will know there aren't blocks lying around with broken nbt data from your previous buggy code

Ok i created a new VOID world, put a teleporter without anything in it and teleported 500 blocks away, an that crashed my game with the exact same error, what the hell

/*Synchronization to the client*/
    @Nullable
    @Override
    public Packet<ClientGamePacketListener> getUpdatePacket() {
        return ClientboundBlockEntityDataPacket.create(this);
    }
    @Override
    public CompoundTag getUpdateTag() {
        return this.saveWithoutMetadata();
    }
    @Override
    public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) {
        super.onDataPacket(net, pkt);
    }

 

Posted (edited)
    @Override
    public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) {
        super.onDataPacket(net, pkt);
    }

This is still redundant.

 

Did you change the other code?

You know your level.getBlockEntity(BlockPos) code is running on both the client and server?

Doing it on the client is unsafe unless you check Level.isLoaded(BlockPos) first.

But as I said, you shouldn't need to call that method since you already have the block entity as a parameter.

Edited by warjort

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

Posted

Another solution would be to just not tick your block on the client.

Looking at your code, I don't see a reason why you need to do this?

Only ticking on the server would simplify your code and you wouldn't have to worry about sides.

See AbstractFurnaceBlock.createFurnaceTicker() for how to create a block entity ticker that only ticks on the server.

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

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

    • Back then there was a number which determined the tier of an item and block. If the block tier is lower or equal to the item number, the block would be mined. this however, has changed and now it goes by "needs_netherite_tool" which is fine, until you realized that some mods had items and blocks that exceeded these values. You can make you own "needs_mod_tool" but I feel that this is more limiting(and just more work) than before. So is there anyway to use something similar to the old tier system while also still being compatible with a lot of other mod tools?
    • Well, when I log in to the server, sometimes within an hour, sometimes within a minute, the server closes and informs me that there was a Ticking entity error. Below is the crash report
    • This forum is for Forge, not NeoForge. Please go to them for support.
    • Forge version: 55.0.0 Minecraft version: 1.21.5 Downloads: As this is the start of a new version, it is recommended that you check the downloads page and use the latest version to receive any bug fixes. Downloads page Intro: Good evening! Today, we have released our initial build of Forge 55.0 for Minecraft 1.21.5. 1.21.5 is the newest member of the 1.21 family of versions, which was released yesterday on March 25, 2025. As a reminder, the first minor (X.0) of a Forge version is a beta. Forge betas are marked as such on the bottom left of the title screen and are candidates for any breaking changes. Additionally, there are a couple of important things to note about this update, which I've made sure to mention in this post as well. Feel free to chat with us about bugs or these implementation changes on GitHub and in our Discord server. As always, we will continue to keep all versions of 1.21 and 1.20 in active support as covered by our tiered support policy. Cheers, happy modding, and good luck porting! Rendering Refactor For those who tuned in to Minecraft Live on March 22, 2025, you may already know that Mojang have announced their intention to bring their new Vibrant Visuals overhaul to Java in the future. They've taken the first steps toward this by refactoring how rendering pipelines and render types are handled internally. This has, in turn, made many of Forge's rendering APIs that have existed for years obsolete, as they (for the most part) can be done directly in vanilla. If there was a rendering API that was provided by Forge which you believe should be re-implemented, we're happy to discuss on GitHub through an issue or a pull request. Deprecation of weapon-like ToolActions In 1.21.5, Minecraft added new data components for defining the characteristics of weapons in data. This includes attack speed, block tags which define efficient blocks, and more. As such, we will begin marking our ToolActions solution for this as deprecated. ToolActions were originally added to address the problem of creating modded tools that needed to perform the same actions as vanilla tools. There are still a few tool actions that will continue to be used, such as the shears tool action for example. There are some existing Forge tool actions that are currently obsolete and have no effect given the way the new data components are implemented. We will continue to work on these deprecations and invite you to chat with us on GitHub or Discord if you have any questions.
  • Topics

×
×
  • Create New...

Important Information

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