Jump to content

[Solved] [1.13.2] Open GUI in Block#onBlockActivated


Recommended Posts

Posted (edited)

I am trying to make a GUI open when my block is clicked. My current code for Block#onBlockActivated is as such:

@Override
public boolean onBlockActivated(IBlockState state, World world, BlockPos pos, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) {
	if (!world.isRemote() && player instanceof EntityPlayerMP) {
		TileEntity tileEntity = world.getTileEntity(pos);
		if (tileEntity instanceof TileEntityMobFarm) {
			NetworkHooks.openGui((EntityPlayerMP) player, new InteractionObjectMobFarm((TileEntityMobFarm) tileEntity));
		}
	}
	return true;
}

 

I also registered the GUI as such:

ModLoadingContext.get().registerExtensionPoint(ExtensionPoint.GUIFACTORY, () -> {
	return (openContainer) -> {
		ResourceLocation location = openContainer.getId();
		if (location.toString().equals(Reference.MOD_ID + ":mob_farm_gui")) {
			EntityPlayerSP player = Minecraft.getInstance().player;
			BlockPos pos = openContainer.getAdditionalData().readBlockPos(); // This line gives the error.
			TileEntity tileEntity = player.world.getTileEntity(pos);
			if (tileEntity instanceof TileEntityMobFarm) {
				return new GuiMobFarm(player.inventory, (TileEntityMobFarm) tileEntity);
			}
		}
		return null;
	};
});

 

However, it seems that the openContainer.getAdditionalData PacketBuffer does not contain the BlockPos data of the block that is clicked by the player, as calling the readBlockPos method gives the following error:

java.lang.IndexOutOfBoundsException
        at io.netty.buffer.EmptyByteBuf.readLong(EmptyByteBuf.java:601)
        at net.minecraft.network.PacketBuffer.readLong(PacketBuffer.java:749)
        at net.minecraft.network.PacketBuffer.readBlockPos(PacketBuffer.java:135)
        at cn.davidma.tinymobfarm.common.TinyMobFarm.lambda$null$0(TinyMobFarm.java:59)
        at net.minecraftforge.fml.network.FMLPlayMessages$OpenContainer.lambda$null$0(FMLPlayMessages.java:193)
        at java.util.Optional.map(Optional.java:215)
        at net.minecraftforge.fml.network.FMLPlayMessages$OpenContainer.lambda$null$2(FMLPlayMessages.java:193)
        at java.util.Optional.ifPresent(Optional.java:159)
        at net.minecraftforge.fml.network.FMLPlayMessages$OpenContainer.lambda$handle$3(FMLPlayMessages.java:192)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at net.minecraft.client.Minecraft.addScheduledTask(Minecraft.java:1851)
        at net.minecraft.client.Minecraft.addScheduledTask(Minecraft.java:1864)
        at net.minecraftforge.fml.network.NetworkEvent$Context.enqueueWork(NetworkEvent.java:176)
        at net.minecraftforge.fml.network.FMLPlayMessages$OpenContainer.handle(FMLPlayMessages.java:192)
        at net.minecraftforge.fml.network.simple.IndexedMessageCodec.lambda$tryDecode$3(IndexedMessageCodec.java:114)
        at java.util.Optional.ifPresent(Optional.java:159)
        at net.minecraftforge.fml.network.simple.IndexedMessageCodec.tryDecode(IndexedMessageCodec.java:114)
        at net.minecraftforge.fml.network.simple.IndexedMessageCodec.consume(IndexedMessageCodec.java:147)
        at net.minecraftforge.fml.network.simple.SimpleChannel.networkEventListener(SimpleChannel.java:64)
        at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
        at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
        at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
        at java.util.stream.Streams$StreamBuilderImpl.forEachRemaining(Streams.java:419)
        at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
        at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
        at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
        at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
        at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
        at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
        at net.minecraftforge.eventbus.EventBus.lambda$addListener$11(EventBus.java:201)
        at net.minecraftforge.eventbus.EventBus.post(EventBus.java:257)
        at net.minecraftforge.fml.network.NetworkInstance.dispatch(NetworkInstance.java:82)
        at net.minecraftforge.fml.network.NetworkHooks.lambda$onCustomPayload$0(NetworkHooks.java:75)
        at java.util.Optional.map(Optional.java:215)
        at net.minecraftforge.fml.network.NetworkHooks.onCustomPayload(NetworkHooks.java:75)
        at net.minecraft.client.network.NetHandlerPlayClient.handleCustomPayload(NetHandlerPlayClient.java:1619)
        at net.minecraft.network.play.server.SPacketCustomPayload.processPacket(SPacketCustomPayload.java:50)
        at net.minecraft.network.play.server.SPacketCustomPayload.processPacket(SPacketCustomPayload.java:11)
        at net.minecraft.network.PacketThreadUtil.func_210405_a(SourceFile:10)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at net.minecraft.util.Util.runTask(SourceFile:199)
        at net.minecraft.client.Minecraft.runGameLoop(Minecraft.java:761)
        at net.minecraft.client.Minecraft.run(Minecraft.java:358)
        at net.minecraft.client.main.Main.main(SourceFile:144)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at net.minecraftforge.userdev.FMLUserdevClientLaunchProvider.lambda$launchService$0(FMLUserdevClientLaunchProvider.java:55)
        at cpw.mods.modlauncher.LaunchServiceHandlerDecorator.launch(LaunchServiceHandlerDecorator.java:19)
        at cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:35)
        at cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:53)
        at cpw.mods.modlauncher.Launcher.run(Launcher.java:58)
        at cpw.mods.modlauncher.Launcher.main(Launcher.java:44)
        at net.minecraftforge.userdev.UserdevLauncher.main(UserdevLauncher.java:77)

 

How would I get the BlockPos of the block from the OpenContainer inside the lambda?

 

If needed, my code is at: https://github.com/davidmaamoaix/TinyMobFarm/tree/1.13.2

Edited by DavidM

Some tips:

Spoiler

Modder Support:

Spoiler

1. Do not follow tutorials on YouTube, especially TechnoVision (previously called Loremaster) and HarryTalks, due to their promotion of bad practice and usage of outdated code.

2. Always post your code.

3. Never copy and paste code. You won't learn anything from doing that.

4. 

Quote

Programming via Eclipse's hotfixes will get you nowhere

5. Learn to use your IDE, especially the debugger.

6.

Quote

The "picture that's worth 1000 words" only works if there's an obvious problem or a freehand red circle around it.

Support & Bug Reports:

Spoiler

1. Read the EAQ before asking for help. Remember to provide the appropriate log(s).

2. Versions below 1.11 are no longer supported due to their age. Update to a modern version of Minecraft to receive support.

 

 

Posted (edited)

NetworkHooks#openGui() should take three arguments, and you're only passing two.  The third argument is a PacketBuffer, where you send any extra data you need on the client side, including in your case the tile entity position.  E.g.:

NetworkHooks.openGui((EntityPlayerMP) player, yourContainerProvider, buf -> buf.writeBlock(tePos));

Edit: third parameter is now a Consumer<PacketBuffer> as @loordgekpointed out.  That changed in the last 24 hours, time to update :)

Edited by desht
  • Like 1
Posted (edited)

update forge, it got changed

    public static void openGui(EntityPlayerMP player, IInteractionObject containerSupplier, Consumer<PacketBuffer> extraDataWriter)

 

Edited by loordgek
  • Like 1
  • Thanks 1
Posted (edited)

Thanks everyone!

Edited by DavidM

Some tips:

Spoiler

Modder Support:

Spoiler

1. Do not follow tutorials on YouTube, especially TechnoVision (previously called Loremaster) and HarryTalks, due to their promotion of bad practice and usage of outdated code.

2. Always post your code.

3. Never copy and paste code. You won't learn anything from doing that.

4. 

Quote

Programming via Eclipse's hotfixes will get you nowhere

5. Learn to use your IDE, especially the debugger.

6.

Quote

The "picture that's worth 1000 words" only works if there's an obvious problem or a freehand red circle around it.

Support & Bug Reports:

Spoiler

1. Read the EAQ before asking for help. Remember to provide the appropriate log(s).

2. Versions below 1.11 are no longer supported due to their age. Update to a modern version of Minecraft to receive support.

 

 

Posted (edited)
1 hour ago, desht said:

Edit: third parameter is now a Consumer<PacketBuffer> as @loordgekpointed out.  That changed in the last 24 hours, time to update :)

Just realized that the method changed in the update.

How would I get a Consumer<PacketBuffer> from a PacketBuffer? From a look of the source code, I assume it requires a method that writes to another PacketBuffer, something like PacketBuffer#writeBytes?

 

Fixed. Thanks for all of your help.

Edited by DavidM

Some tips:

Spoiler

Modder Support:

Spoiler

1. Do not follow tutorials on YouTube, especially TechnoVision (previously called Loremaster) and HarryTalks, due to their promotion of bad practice and usage of outdated code.

2. Always post your code.

3. Never copy and paste code. You won't learn anything from doing that.

4. 

Quote

Programming via Eclipse's hotfixes will get you nowhere

5. Learn to use your IDE, especially the debugger.

6.

Quote

The "picture that's worth 1000 words" only works if there's an obvious problem or a freehand red circle around it.

Support & Bug Reports:

Spoiler

1. Read the EAQ before asking for help. Remember to provide the appropriate log(s).

2. Versions below 1.11 are no longer supported due to their age. Update to a modern version of Minecraft to receive support.

 

 

Posted
4 minutes ago, DavidM said:

Just realized that the method changed in the update.

How would I get a Consumer<PacketBuffer> from a PacketBuffer? From a look of the source code, I assume it requires a method that writes to another PacketBuffer, something like PacketBuffer#writeBytes?

 Thanks.

 

Instead of constructing the PacketBuffer, writing to it and then calling openGui, simply call openGui with a lambda function that writes to the supplied PacketBuffer. Forge constructs the PacketBuffer for you.

  • Like 1

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

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

    • that happens every time I enter a new dimension.
    • This is the last line before the crash: [ebwizardry]: Synchronising spell emitters for PixelTraveler But I have no idea what this means
    • What in particular? I barely used that mod this time around, and it's never been a problem in the past.
    • Im trying to build my mod using shade since i use the luaj library however i keep getting this error Reason: Task ':reobfJar' uses this output of task ':shadowJar' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. So i try adding reobfJar.dependsOn shadowJar  Could not get unknown property 'reobfJar' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. my gradle file plugins { id 'eclipse' id 'idea' id 'maven-publish' id 'net.minecraftforge.gradle' version '[6.0,6.2)' id 'com.github.johnrengelman.shadow' version '7.1.2' id 'org.spongepowered.mixin' version '0.7.+' } apply plugin: 'net.minecraftforge.gradle' apply plugin: 'org.spongepowered.mixin' apply plugin: 'com.github.johnrengelman.shadow' version = mod_version group = mod_group_id base { archivesName = mod_id } // Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. java.toolchain.languageVersion = JavaLanguageVersion.of(17) //jarJar.enable() println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" minecraft { mappings channel: mapping_channel, version: mapping_version copyIdeResources = true runs { configureEach { workingDirectory project.file('run') property 'forge.logging.markers', 'REGISTRIES' property 'forge.logging.console.level', 'debug' arg "-mixin.config=derp.mixin.json" mods { "${mod_id}" { source sourceSets.main } } } client { // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. property 'forge.enabledGameTestNamespaces', mod_id } server { property 'forge.enabledGameTestNamespaces', mod_id args '--nogui' } gameTestServer { property 'forge.enabledGameTestNamespaces', mod_id } data { workingDirectory project.file('run-data') args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') } } } sourceSets.main.resources { srcDir 'src/generated/resources' } repositories { flatDir { dirs './libs' } maven { url = "https://jitpack.io" } } configurations { shade implementation.extendsFrom shade } dependencies { minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" implementation 'org.luaj:luaj-jse-3.0.2' implementation fg.deobf("com.github.Virtuoel:Pehkui:${pehkui_version}") annotationProcessor 'org.spongepowered:mixin:0.8.5:processor' minecraftLibrary 'luaj:luaj-jse:3.0.2' shade 'luaj:luaj-jse:3.0.2' } // Example for how to get properties into the manifest for reading at runtime. tasks.named('jar', Jar).configure { manifest { attributes([ 'Specification-Title' : mod_id, 'Specification-Vendor' : mod_authors, 'Specification-Version' : '1', // We are version 1 of ourselves 'Implementation-Title' : project.name, 'Implementation-Version' : project.jar.archiveVersion, 'Implementation-Vendor' : mod_authors, 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", "TweakOrder" : 0, "MixinConfigs" : "derp.mixin.json" ]) } rename 'mixin.refmap.json', 'derp.mixin-refmap.json' } shadowJar { archiveClassifier = '' configurations = [project.configurations.shade] finalizedBy 'reobfShadowJar' } assemble.dependsOn shadowJar reobf { re shadowJar {} } publishing { publications { mavenJava(MavenPublication) { artifact jar } } repositories { maven { url "file://${project.projectDir}/mcmodsrepo" } } } my entire project:https://github.com/kevin051606/DERP-Mod/tree/Derp-1.0-1.20
  • Topics

×
×
  • Create New...

Important Information

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