Jump to content

Recommended Posts

Posted (edited)

I got another tile entity, with yet another problem.. When I right click it, it does nothing, but when I click the barrel(the other tile entity I had problems with) it opens.

Gui Handler:

public class GuiHandler {
	public static GuiScreen openGui(FMLPlayMessages.OpenContainer openContainer) {
		BlockPos pos = openContainer.getAdditionalData().readBlockPos();
		EntityPlayerSP player = Minecraft.getInstance().player;
		
		//Barrel
		if(openContainer.getId().equals(new ResourceLocation(Main.modid, "barrel"))) {
			return new GuiBarrel(player.inventory, (TileEntityBarrel)Minecraft.getInstance().world.getTileEntity(pos), player);
		}
		if(openContainer.getId().equals(new ResourceLocation(Main.modid, "press"))) {
			return new GuiPress(player.inventory, (TileEntityPress)Minecraft.getInstance().world.getTileEntity(pos));
		}
		
		return null;
	}
	
	public static enum GUI {
		BARREL("moresimplestuff:barrel", new ResourceLocation(Main.modid, "textures/gui/barrel.png")),
		PRESS("moresimplestuff:press", new ResourceLocation(Main.modid, "textures/gui/press.png"));
    	
    	private ResourceLocation texture;
    	private String guiId;
    	
    	GUI(String guiId, ResourceLocation texture) {
    		this.guiId = guiId;
    		this.texture = texture;
    	}
    	
    	public String getGuiID() {
    		return guiId;
    	}
    	
    	public ResourceLocation getTexture() {
    		return texture;
    	}
	}
}

How I registered it (in my main class):

ModLoadingContext.get().registerExtensionPoint(ExtensionPoint.GUIFACTORY, () -> GuiHandler::openGui);

And how I open it (block class): 

@Override
	public boolean onBlockActivated(IBlockState state, World worldIn, BlockPos pos, EntityPlayer player, EnumHand hand,
			EnumFacing side, float hitX, float hitY, float hitZ) {
		if (worldIn.isRemote) {
			return true;
		} else {
			TileEntityPress te = (TileEntityPress)worldIn.getTileEntity(pos);
			
			if(te != null) {
				if(player instanceof EntityPlayerMP && !(player instanceof FakePlayer)) {
					EntityPlayerMP playermp = (EntityPlayerMP)player;
					
					NetworkHooks.openGui(playermp, te, buf -> buf.writeBlockPos(pos));
				}
			}
			
			return true;
		}
	}

If you need to me to show other code, just tell me

Edited by MyRedAlien43
Posted
4 hours ago, diesieben07 said:

Show your tile entity and container class.

Tile Entity:

package beta.mod.tileentity.press;

import beta.mod.init.ItemInit;
import beta.mod.tileentity.ModTET;
import beta.mod.util.GuiHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.IInteractionObject;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.ItemStackHandler;

@SuppressWarnings("unused")
public class TileEntityPress extends TileEntity implements ITickable, IInteractionObject {
	public ItemStackHandler handler = new ItemStackHandler(3);
	private int burnTime, currentBurnTime, cookTime, totalCookTime;
	private ITextComponent customName;
	
	private TileEntityPress(TileEntityType<?> type) {
		super(type);
	}
	
	public TileEntityPress() {
		this(ModTET.PRESS);
	}
	
	@Override
	public ITextComponent getName() {
		return this.hasCustomName() ? this.customName : new TextComponentTranslation("container.press");
	}
	
	@Override
	public boolean hasCustomName() {
		return this.customName != null;
	}
	
	public void setCustomName(ITextComponent customName) {
		this.customName = customName;
	}
	
	@Override
	public void read(NBTTagCompound compound) {
		super.read(compound);
		this.handler.deserializeNBT(compound.getCompound("inventory"));
		this.burnTime = compound.getInt("BurnTime");
		this.cookTime = compound.getInt("CookTime");
		this.totalCookTime = compound.getInt("TotalCookTime");
		this.currentBurnTime = compound.getInt("CurrentBurnTime");
		
		if(compound.contains("CustomName", Constants.NBT.TAG_STRING)) {
			this.customName = ITextComponent.Serializer.fromJson(compound.getString("CustomName"));
		}
	}
	
	@Override
	public NBTTagCompound write(NBTTagCompound compound) {
		super.write(compound);
		compound.setTag("inventory", this.handler.serializeNBT());
		compound.setInt("BurnTime", this.burnTime);
		compound.setInt("CookTime", this.cookTime);
		compound.setInt("TotalCookTime", this.totalCookTime);
		compound.setInt("CurrentBurnTime", this.currentBurnTime);
		if(this.hasCustomName()) {
			compound.setString("CustomName", ITextComponent.Serializer.toJson(customName));
		}
		
		return compound;
	}
	
	public boolean isPressing() {
		return this.burnTime > 0;
	}
	
	@Override
	public void tick() {
		boolean flag = this.isPressing(), flag1 = false;
		
		if(this.isPressing()) {
			this.burnTime--;
		}
		
		if(!this.world.isRemote) {
			ItemStack stack = this.handler.getStackInSlot(1);
			
			if(this.isPressing() || !stack.isEmpty() && !this.handler.getStackInSlot(0).isEmpty()) {
				if(!this.isPressing() && this.canSmelt()) {
					this.burnTime = getBurnTime(stack);
					this.currentBurnTime = this.burnTime;
					
					if(this.isPressing()) {
						flag1 = true;
						
						if(!stack.isEmpty()) {
							Item item = stack.getItem();
							stack.shrink(1);
							
							if(stack.isEmpty()) {
								ItemStack item1 = item.getContainerItem(stack);
								this.handler.setStackInSlot(1, item1);
							}
						}
					}
				}
				
				if(this.isPressing() && this.canSmelt()) {
					this.cookTime++;
					
					if(this.cookTime == this.totalCookTime) {
						this.cookTime = 0;
						this.totalCookTime = this.getCookTime(this.handler.getStackInSlot(0));
						this.smeltItem();
						flag1 = true;
					}
				} else {
					this.cookTime = 0;
				}
			} else if(!this.isPressing() && this.cookTime > 0) {
				this.cookTime = MathHelper.clamp(this.cookTime - 2, 0, this.totalCookTime);
			}
			
			if(flag != this.isPressing()) {
				flag1 = true;
				BlockPress.setState(this.isPressing(), this.world, this.pos);
			}
		}
	}

	public void dropInventoryItems(World worldIn, BlockPos pos) {
		for(int i = 0; i < this.handler.getSlots(); i++) {
			ItemStack stack = this.handler.getStackInSlot(i);
			
			if(!stack.isEmpty()) {
				InventoryHelper.spawnItemStack(worldIn, (double)pos.getX(), (double)pos.getY(), (double)pos.getZ(), stack);
			}
		}
	}
	
	public int getCookTime(ItemStack stack) {
		return 200;
	}
	
	private boolean canSmelt() {
		if(this.handler.getStackInSlot(0).isEmpty()) {
			return false;
		} else {
			ItemStack stack = PressRecipes.instance().getCookingResult(this.handler.getStackInSlot(0));
			
			if(stack.isEmpty()) {
				return false;
			} else {
				ItemStack stack1 = this.handler.getStackInSlot(2);
				
				if(stack1.isEmpty()) {
					return true;
				} else if(!stack1.isItemEqual(stack)) {
					return false;
				} else if(stack1.getCount() + stack.getCount() <= 64 && stack1.getCount() + stack.getCount() <= stack1.getMaxStackSize()) {
					return true;
				} else {
					return stack1.getCount() + stack.getCount() <= stack.getMaxStackSize();
				}
			}
		}
	}
	
	public void smeltItem() {
		if(this.canSmelt()) {
			ItemStack stack = this.handler.getStackInSlot(0), stack1 = PressRecipes.instance().getCookingResult(stack), stack2 = this.handler.getStackInSlot(2);
			
			if(stack2.isEmpty()) {
				this.handler.setStackInSlot(2, stack1.copy());
			} else if(stack2.getItem() == stack1.getItem()) {
				stack2.grow(stack1.getCount());
			}
			
			if(stack.getItem() == Blocks.WET_SPONGE.asItem() && !this.handler.getStackInSlot(1).isEmpty() && this.handler.getStackInSlot(1).getItem() == Items.BUCKET) {
				this.handler.setStackInSlot(1, new ItemStack(Items.WATER_BUCKET));
			}
			
			stack.shrink(1);
		}
	}
	
	@SuppressWarnings("unlikely-arg-type")
	public static int getBurnTime(ItemStack stack) {
		if(stack.isEmpty()) {
			return 0;
		} else {
			int burnTime = net.minecraft.tileentity.TileEntityFurnace.getBurnTimes().get(stack);
			if(burnTime >= 0) return burnTime;
			Item item = stack.getItem();
			
			if(item == ItemInit.GRAPE) {
				return 20;
			}
		}
		
		return 200;
	}
	
	public static boolean isItemFuel(ItemStack stack) {
		return getBurnTime(stack) > 0;
	}
	
	@Override
	public String getGuiID() {
		return GuiHandler.GUI.PRESS.getGuiID();
	}
	
	@Override
	public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn) {
		return new ContainerPress(playerInventory, this);
	}
	
	public int getField(int id) {
		switch(id) {
		case 0:
			return this.burnTime;
		case 1:
			return this.currentBurnTime;
		case 2:
			return this.cookTime;
		case 3:
			return this.totalCookTime;
		default:
			return 0;
		}
	}
	
	public void setField(int id, int value) {
		switch(id) {
		case 0:
			this.burnTime = value;
			break;
		case 1:
			this.currentBurnTime = value;
			break;
		case 2:
			this.cookTime = value;
			break;
		case 3:
			this.totalCookTime = value;
			break;
		}
	}
	
	public int getFieldCount() {
		return 4;
	}
	
	public void clear() {
		for(int i = 0; i < this.handler.getSlots(); i++) {
			this.handler.setStackInSlot(i, ItemStack.EMPTY);
		}
	}
	
	public ItemStackHandler getInventory() {
		return this.handler;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public <T> LazyOptional<T> getCapability(Capability<T> cap) {
		if(!this.removed && cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
			return LazyOptional.of(() -> (T)handler);
		} else {
			return LazyOptional.empty();
		}
	}

	@Override
	public ITextComponent getCustomName() {
		return this.hasCustomName() ? this.customName : new TextComponentTranslation("Press");
	}
}

(I made setField and getField, not from IInventory)

Container:

package beta.mod.tileentity.press;

import beta.mod.tileentity.press.slots.SlotPressFuel;
import beta.mod.tileentity.press.slots.SlotPressOutput;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IContainerListener;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.SlotItemHandler;

public class ContainerPress extends Container {
	private final TileEntityPress te;
	private int cookTime, totalCookTime, burnTime, currentBurnTime;
	
	public ContainerPress(InventoryPlayer plrInv, TileEntityPress te) {
		this.te = te;
		this.addSlot(new SlotItemHandler(te.getInventory(), 0, 56, 53));
		this.addSlot(new SlotPressFuel(te.getInventory(), 1, 56, 17));
		this.addSlot(new SlotPressOutput(plrInv.player, te.getInventory(), 2, 116, 35));
		
		for(int i = 0; i < 3; i++)
		{
			for(int j = 0; j < 9; ++j)
			{
				this.addSlot(new Slot(plrInv, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));
			}
		}
		
		for(int k = 0; k < 9; k++)
		{
			this.addSlot(new Slot(plrInv, k, 8 + k * 18, 142));
		}
	}
	
	@Override
	public void detectAndSendChanges() {
		super.detectAndSendChanges();
		
		for(int i = 0; i < this.listeners.size(); i++) {
			IContainerListener icontainerlistener = this.listeners.get(i);

	        if (this.cookTime != this.te.getField(2))
	        {
	            icontainerlistener.sendWindowProperty(this, 2, this.te.getField(2));
	        }

	        if (this.burnTime != this.te.getField(0))
	        {
	            icontainerlistener.sendWindowProperty(this, 0, this.te.getField(0));
	        }

	        if (this.currentBurnTime != this.te.getField(1))
	        {
	            icontainerlistener.sendWindowProperty(this, 1, this.te.getField(1));
	        }

	        if (this.totalCookTime != this.te.getField(3))
	        {
	            icontainerlistener.sendWindowProperty(this, 3, this.te.getField(3));
	        }
		}
	    this.cookTime = this.te.getField(2);
	    this.burnTime = this.te.getField(0);
	    this.currentBurnTime = this.te.getField(1);
	    this.totalCookTime = this.te.getField(3);
	}
	
	@Override
	public void updateProgressBar(int id, int data) {
		this.te.setField(id, data);
	}
	
	@Override
	public boolean canInteractWith(EntityPlayer playerIn) {
		return playerIn.getDistanceSq((double)te.getPos().getX() + 0.5d, (double)te.getPos().getY() + 0.5d, (double)te.getPos().getZ() + 0.5d) <= 64.0d;
	}
	
	@Override
	public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) {
		ItemStack itemstack = ItemStack.EMPTY;
        Slot slot = this.inventorySlots.get(index);

        if (slot != null && slot.getHasStack())
        {
            ItemStack itemstack1 = slot.getStack();
            itemstack = itemstack1.copy();

            if (index == 2)
            {
                if (!this.mergeItemStack(itemstack1, 3, 39, true))
                {
                    return ItemStack.EMPTY;
                }

                slot.onSlotChange(itemstack1, itemstack);
            }
            else if (index != 1 && index != 0)
            {
                if (!PressRecipes.instance().getCookingResult(itemstack1).isEmpty())
                {
                    if (!this.mergeItemStack(itemstack1, 0, 1, false))
                    {
                        return ItemStack.EMPTY;
                    }
                }
                else if (TileEntityPress.isItemFuel(itemstack1))
                {
                    if (!this.mergeItemStack(itemstack1, 1, 2, false))
                    {
                        return ItemStack.EMPTY;
                    }
                }
                else if (index >= 3 && index < 30)
                {
                    if (!this.mergeItemStack(itemstack1, 30, 39, false))
                    {
                        return ItemStack.EMPTY;
                    }
                }
                else if (index >= 30 && index < 39 && !this.mergeItemStack(itemstack1, 3, 30, false))
                {
                    return ItemStack.EMPTY;
                }
            }
            else if (!this.mergeItemStack(itemstack1, 3, 39, false))
            {
                return ItemStack.EMPTY;
            }

            if (itemstack1.isEmpty())
            {
                slot.putStack(ItemStack.EMPTY);
            }
            else
            {
                slot.onSlotChanged();
            }

            if (itemstack1.getCount() == itemstack.getCount())
            {
                return ItemStack.EMPTY;
            }

            slot.onTake(playerIn, itemstack1);
        }

        return itemstack;
	}
}

 

Posted (edited)
1 hour ago, diesieben07 said:

Can't see anything wrong at a glance. Have you used the debugger?

Sorry for being dumb but where/what is it?

Edited by MyRedAlien43
Posted (edited)
1 minute ago, diesieben07 said:

Where did you put breakpoints? Did they get hit?

They didn't get hit.. I tried putting it in the block and the tile entity

Edited by MyRedAlien43
Posted
3 minutes ago, diesieben07 said:

Dude. Can you stop being so vague?
Where exactly did you put breakpoints?

NetworkHooks.openGui(playermp, te, buf -> buf.writeBlockPos(pos));
return new ContainerPress(playerInventory, this);
return GuiHandler.GUI.PRESS.getGuiID();

 

Posted
4 minutes ago, diesieben07 said:

Okay. If the first line is not triggered, obviously the other two can't trigger as well.

Now, try to use some logical reasoning. You have various if statements in onBlockActivated, so if it's not getting to openGui some condition before that is not true. Use the debugger to find out what is not true any why.

I put a break point on the line:

if(worldIn.isRemote) {
	return true; //This line
}

And it triggered, and not the other one I put on the line:

TileEntityPress te = (TileEntityPress)worldIn.getTileEntity(pos);

that is on the else side of the if above

Posted (edited)
10 minutes ago, loordgek said:

you override hasTileEntity but not createTileEntity

Omfg im so dumb... if i knew i didnt override it... thanks it works now i really want to bang my head onto a wall

Also thanks for the help @diesieben07 i appreciate it

Edited by MyRedAlien43
Posted

I propose adding a "3. LEARN TO USE YOUR IDE's DEBUGGER!" entry under General Issues in your Common Issues / Recommendations post.

@MyRedAlien43seriously, the debugger is a lifesaver.  Modding without it is like trying to run with your shoelaces tied together.

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.