Jump to content

Recommended Posts

Posted

Alright, so I fixed my issues from earlier. I'm so close to being done with this inventory work. But, after going through CoolAlias' tutorial on inventory, updates and all, my new custom slots don't save. You can place an item in whichever slot, but when you close and reopen the GUI, the item is deleted forever. So sad  :'( hehe.

 

So I did some searching, saw some previous posts on this issue but never found any solutions for my issue.

 

Inventory Class:

 

 

// I removed a bunch of the code because you shouldn't need most of it.

// Some variables
protected ItemStack[] inventory = new ItemStack[3];
public int slotsCount = 3;
private String tagName = Rot.MOD_ID + "TrinketInventory";

// Read/Write NBT Methods
public void writeToNBT(NBTTagCompound tagcompound)
{
	NBTTagList nbttaglist = new NBTTagList();
	for (int i = 0; i < this.getSizeInventory(); ++i)
	{
		if (this.getStackInSlot(i) != null)
		{
			NBTTagCompound nbttagcompound1 = new NBTTagCompound();
			nbttagcompound1.setByte("Slot", (byte) i);
			this.getStackInSlot(i).writeToNBT(nbttagcompound1);
			nbttaglist.appendTag(nbttagcompound1);
		}
	}
	// We're storing our items in a custom tag list using our 'tagName' from
	// above
	// to prevent potential conflicts
	tagcompound.setTag(tagName, nbttaglist);
}

public void readFromNBT(NBTTagCompound compound) {
	// now you must include the NBTBase type ID when getting the list;
	// NBTTagCompound's ID is 10
	NBTTagList items = compound.getTagList(tagName, compound.getId());
	for (int i = 0; i < items.tagCount(); ++i) {
		// tagAt(int) has changed to getCompoundTagAt(int)
		NBTTagCompound item = items.getCompoundTagAt(i);
		byte slot = item.getByte("Slot");
		if (slot >= 0 && slot < getSizeInventory()) {
			setInventorySlotContents(slot,
					ItemStack.loadItemStackFromNBT(item));
		}
	}
}

 

 

 

ExtendPlayer:

 

 

// Some Variables
public final RotTrinketInventory inventory = new RotTrinketInventory();

// get and register
public static final ExtendPlayer get(EntityPlayer player)
{
	try
	{
		return (ExtendPlayer) player.getExtendedProperties(EXT_PROP_NAME);
	}
	catch (Exception e)
	{
		return null;
	}
}

public static final void register(EntityPlayer player)
{
	player.registerExtendedProperties(ExtendPlayer.EXT_PROP_NAME, new ExtendPlayer(player));
}


// Load and Save NBT Data
@Override
public void loadNBTData(NBTTagCompound compound)
{
	// Here we fetch the unique tag compound we set for this class of
	// Extended Properties
	NBTTagCompound properties = (NBTTagCompound) compound.getTag(EXT_PROP_NAME);
	// Snipped out a bunch of other loads you don't need.
	this.inventory.readFromNBT(properties);

}

@Override
public void saveNBTData(NBTTagCompound compound)
{
	// We need to create a new tag compound that will save everything for
	// our Extended Properties
	NBTTagCompound properties = new NBTTagCompound();

	// Again I removed a ton of saves you don't need.

	this.inventory.writeToNBT(properties);

	compound.setTag(EXT_PROP_NAME, properties);
}

 

 

 

Should be all the code you'd need; I don't think it's a container issue, but idk.

 

Once more, any help is appreciated.  :-\

Posted

That looks like it should be saving and loading correctly - are you providing a proper server-side gui element, i.e. a Container, when opening your gui? Is that container using the player's custom inventory field?

 

Show your IGuiHandler code as well as your Container constructor.

 

Container:

 

 

	public ContainerPseudoPlayer(InventoryPlayer realPlayerInventory, EntityPlayer player)
{
	int i;
        int j;
        
        // Inventory
	for (i = 0; i < 3; ++i)
        {
            for (j = 0; j < 9; ++j)
            {
                this.addSlotToContainer(new Slot(realPlayerInventory, j + (i + 1) * 9, 8 + j * 18, 84 + i * 18));
            }
        }

	// Hotbar
	for (i = 0; i < 9; ++i)
        {
            this.addSlotToContainer(new Slot(realPlayerInventory, i, 8 + i * 18, 142));
        }

	// Trinkets
	for (i = 0; i < 3; i++)
	{
		this.addSlotToContainer(new Slot(new RotTrinketInventory(), i, 26, 8 + i * 18));
	}

	// Armor, literally copy-pasted from container-player
	 for (i = 0; i < 4; ++i)
        {
            final int k = i;
            this.addSlotToContainer(new Slot(realPlayerInventory, realPlayerInventory.getSizeInventory() - 1 - i, 8, 8 + i * 18)
            {
                public int getSlotStackLimit()
                {
                    return 1;
                }
                public boolean isItemValid(ItemStack stack)
                {
                    if (stack == null) return false;
                    return stack.getItem().isValidArmor(stack, k, player);
                }
                @SideOnly(Side.CLIENT)
                public String getSlotTexture()
                {
                    return ItemArmor.EMPTY_SLOT_NAMES[k];
                }
            });
        }
}

 

 

 

GuiHandler:

 

 

public class GuiHandler implements IGuiHandler {
@Override
public Object getClientGuiElement(int guiId, EntityPlayer player, World world, int x,
		int y, int z) {
	// -snip-
	switch (guiId) {
		case 0 :
			// -snip-
		case 1 : {
			return new GuiClassSelection(player);
		}
		default :
			return null;
	}
}
// 1 is class Menu
@Override
public Object getServerGuiElement(int guiId, EntityPlayer player, World world, int x,
		int y, int z) {
	// -snip-

	switch (guiId) {
		case 0 :
			// -snip -
		case 1 : 
			return new ContainerPseudoPlayer(player.inventory, player);
		default :
			return null;
	}
}

}

Snipped out some code for a different gui :P

 

 

Posted

Your issue is that you are not actually passing in the custom player inventory, only the vanilla inventory.

 

Your code should look like this:

return new ContainerCustomPlayer(player, player.inventory, ExtendedPlayer.get(player).inventory);

Note the last parameter is the custom inventory, which you need in your Container class to add the custom inventory slots:

// add one slot to the container for every slot in your custom inventory:
addSlotToContainer(new SlotCustom(inventoryCustom, 0, 80, );

Guest
This topic is now closed to further replies.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • I know that this may be a basic question, but I am very new to modding. I am trying to have it so that I can create modified Vanilla loot tables that use a custom enchantment as a condition (i.e. enchantment present = item). However, I am having trouble trying to implement this; the LootItemRandomChanceWithEnchantedBonusCondition constructor needs a Holder<Enchantment> and I am unable to use the getOrThrow() method on the custom enchantment declared in my mod's enchantments class. Here is what I have so far in the GLM:   protected void start(HolderLookup.Provider registries) { HolderLookup.RegistryLookup<Enchantment> registrylookup = registries.lookupOrThrow(Registries.ENCHANTMENT); LootItemRandomChanceWithEnchantedBonusCondition lootItemRandomChanceWithEnchantedBonusCondition = new LootItemRandomChanceWithEnchantedBonusCondition(0.0f, LevelBasedValue.perLevel(0.07f), registrylookup.getOrThrow(*enchantment here*)); this.add("nebu_from_deepslate", new AddItemModifier(new LootItemCondition[]{ LootItemBlockStatePropertyCondition.hasBlockStateProperties(Blocks.DEEPSLATE).build(), LootItemRandomChanceCondition.randomChance(0.25f).build(), lootItemRandomChanceWithEnchantedBonusCondition }, OrichalcumItems.NEBU.get())); }   Inserting Enchantments.[vanilla enchantment here] actually works but trying to declare an enchantment from my custom enchantments class as [mod enchantment class].[custom enchantment] does not work even though they are both a ResourceKey and are registered in Registries.ENCHANTMENT. Basically, how would I go about making it so that a custom enchantment declared as a ResourceKey<Enchantment> of value ResourceKey.create(Registries.ENCHANTMENT, ResourceLocation.fromNamespaceAndPath([modid], [name])), declared in a seperate enchantments class, can be used in the LootItemRandomChanceWithEnchantedBonusCondition constructor as a Holder? I can't use getOrThrow() because there is no level or block entity/entity in the start() method and it is running as datagen. It's driving me nuts.
    • Hi here is an update. I was able to fix the code so my mod does not crash Minecraft. Please understand that I am new to modding but I honestly am having a hard time understanding how anyone can get this to work without having extensive programming and debugging experience as well as searching across the Internet, multiple gen AI bots (claude, grok, openai), and examining source code hidden in the gradle directory and in various github repositories. I guess I am wrong because clearly there are thousands of mods so maybe I am just a newbie. Ok, rant over, here is a step by step summary so others can save the 3 days it took me to figure this out.   1. First, I am using forge 54.1.0 and Minecraft 1.21.4 2. I am creating a mod to add a shotgun to Minecraft 3. After creating the mod and compiling it, I installed the .jar file to the proper directory in Minecraft and used 1.21.4-forge-54.1.0 4. The mod immediately crashed with the error: Caused by: java.lang.NullPointerException: Item id not set 5. Using the stack trace, I determined that the Exception was being thrown from the net.minecraft.world.item.Item.Properties class 6. It seems that there are no javadocs for this class, so I used IntelliJ which was able to provide a decompiled version of the class, which I then examined to see the source of the error. Side question: Are there javadocs? 7. This method, specifically, was the culprit: protected String effectiveDescriptionId() {      return this.descriptionId.get(Objects.requireNonNull(this.id, "Item id not set"));  } 8. Now my quest was to determine how to set this.id. Looking at the same source file, I determined there was another method:  public Item.Properties setId(ResourceKey<Item> pId) {             this.id = pId;             return this;   } 9. So now, I need to figure out how to call setId(). This required working backwards a bit. Starting from the constructor, I stubbed out the variable p which is of type Item.Properties public static final RegistryObject<Item> SHOTGUN = ITEMS.register("shotgun", () -> new ShotgunItem(p)); Rather than putting this all on one line, I split it up for readability like this: private static final Item.Properties p = new Item.Properties().useItemDescriptionPrefix().setId(rk); Here is was the missing function, setId(), which takes a type of ResourceKey<Item>. My next problem is that due to the apparent lack of documentation (I tried searching the docs on this site) I could not determine the full import path to ResourceKey. I did some random searching on the Internet and stumbled across a Github repository which gave two clues: import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; Then I created the rk variable like this: private static ResourceKey<Item> rk = ResourceKey.create(Registries.ITEM, ResourceLocation.parse("modid:shotgunmod")); And now putting it all together in order: private static ResourceKey<Item> rk = ResourceKey.create(Registries.ITEM, ResourceLocation.parse("modid:shotgunmod")); private static final Item.Properties p = new Item.Properties().useItemDescriptionPrefix().setId(rk); public static final RegistryObject<Item> SHOTGUN = ITEMS.register("shotgun", () -> new ShotgunItem(p)); This compiled and the mod no longer crashes. I still have more to do on it, but hopefully this will save someone hours. I welcome any feedback and if I missed some obvious modding resource or tutorial that has this information. If not, I might suggest we add it somewhere for people trying to write a mod that doesn't crash. Thank you !!!  
    • I will keep adding to this thread with more information in case anyone can help, or at the very least I can keep my troubleshooting organized. I decided to downgrade to 54.1.0 in the hopes that this would fix the issue but it didn't. At least now I am on a "recommended" version. The crash report did confirm my earlier post that the Exception is coming from effectiveDescriptionId(). I'll continue to see if I can find a way to set the ID manually.   Caused by: java.lang.NullPointerException: Item id not set         at java.base/java.util.Objects.requireNonNull(Objects.java:259) ~[?:?]         at TRANSFORMER/[email protected]/net.minecraft.world.item.Item$Properties.effectiveDescriptionId(Item.java:465) ~[forge-1.21.4-54.1.0-client.jar!/:?]         at TRANSFORMER/[email protected]/net.minecraft.world.item.Item.<init>(Item.java:111) ~[forge-1.21.4-54.1.0-client.jar!/:?]         at TRANSFORMER/[email protected]/com.example.shotgunmod.ShotgunItem.<init>(ShotgunItem.java:19) ~[shotgunmod-1.0.0.jar!/:1.0.0]         at TRANSFORMER/[email protected]/com.example.shotgunmod.ModItems.lambda$static$0(ModItems.java:15) ~[shotgunmod-1.0.0.jar!/:1.0.0]         at TRANSFORMER/[email protected]/net.minecraftforge.registries.DeferredRegister$EventDispatcher.lambda$handleEvent      
    • It just randomly stop working after a rebooted my dedicated server PLEASE HELP!   com.google.gson   Failed to start the minecraft server com.google.gson.JsonSyntaxException: Expected a com.google.gson.JsonObject but was com.google.gson.JsonPrimitive; at path $  
  • Topics

×
×
  • Create New...

Important Information

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