Jump to content

[1.14.4] Capability NBT for an ItemStack not loading


Recommended Posts

I have created a custom Capability in order to store ItemStack specific information on a particular item. The Capability functionality works in that each itemstack has its own information. However, the NBT does not appear to be saving and loading correctly, as the values reset upon exiting and reopening the world. After doing some debugging, I determined that the writeNBT function in the storage class is being called, but the readNBT function is not. Is there something I need to do to my Item class to make the Capability Storage work properly? Or is something in my Capability implementation incorrect?

 

Interface:

public interface GunInfo {
	
	public void setClip(int clip);
	public void setReload(int reload);
	public void setRecoil(float recoil, float yaw, float antiyaw, float antirec);
	public void setReloading(boolean reload);
	public void setCooldown(int cd);
	public int getClip();
	public int getReload();
	public float getRecoil();
	public float getYaw();
	public float getAntiYaw();
	public float getAntiRecoil();
	public boolean isReloading();
	public int getCooldown();
	
}

 

Storage class:

public class GunInfoStorage implements IStorage<GunInfo> {

	@Override
	public INBT writeNBT(Capability<GunInfo> capability, GunInfo instance, Direction side) {
		CompoundNBT tag = new CompoundNBT();
		tag.putInt("clip", instance.getClip());
		tag.putInt("reload", instance.getReload());
		tag.putBoolean("reload", instance.isReloading());
		
		return tag;
	
	}

	@Override
	public void readNBT(Capability<GunInfo> capability, GunInfo instance, Direction side, INBT nbt) {
		CompoundNBT tag = (CompoundNBT) nbt;
		
		instance.setClip(tag.getInt("clip"));
		instance.setReload(tag.getInt("reload"));
		instance.setReloading(tag.getBoolean("reload"));
		
	}

}

 

Provider Class:

 

public class GunInfoProvider implements GunInfo, ICapabilitySerializable<INBT> {

	@CapabilityInject(GunInfo.class)
	public static Capability<GunInfo> guninfo = null;
	
	private LazyOptional<GunInfo> instance = LazyOptional.of(guninfo::getDefaultInstance);
	
	@Override
	public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
		return cap == guninfo ? instance.cast() : LazyOptional.empty();
	}

	@Override
	public INBT serializeNBT() {
		return guninfo.getStorage().writeNBT(guninfo, this.instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")), null);
	}

	@Override
	public void deserializeNBT(INBT nbt) {
		guninfo.getStorage().readNBT(guninfo, this.instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")), null, nbt);
		
	}

	public int currentClip;
	public int currentReload;
	public float recoil, yawRecoil, antiYaw, antiRecoil;
	public boolean reloading;
	public int cooldown;

	public void setClip(int clip) {
		currentClip = clip;
	}
	
	public void setReload(int reload) {
		currentReload = reload;
	}
	
	public void setRecoil(float rec, float yaw, float antiyaw, float antirec) {
		recoil = rec;
		yawRecoil = yaw;
		antiYaw = antiyaw;
		antiRecoil = antirec;
	}
	
	@Override
	public void setReloading(boolean reload) {
		reloading = reload;
	}
	
	@Override
	public void setCooldown(int cd) {
		cooldown = cd;
	}

	@Override
	public int getClip() {
		return currentClip;
	}

	@Override
	public int getReload() {
		return currentReload;
	}

	@Override
	public float getRecoil() {
		return recoil;
	}

	@Override
	public float getYaw() {
		return yawRecoil;
	}

	@Override
	public float getAntiYaw() {
		return antiYaw;
	}

	@Override
	public float getAntiRecoil() {
		return antiRecoil;
	}


	@Override
	public boolean isReloading() {
		return reloading;
	}


	@Override
	public int getCooldown() {
		return cooldown;
	}

}

 

AttachCapabilities event function:

 

@Mod.EventBusSubscriber
public class FmlEvents {

    static int capid = 0;
    
	@CapabilityInject(GunInfo.class)
	public static Capability<GunInfo> guninfo = null;
    
    @SubscribeEvent
	public static void onAttachCapabilities(AttachCapabilitiesEvent<ItemStack> event) {
    	
		if (event.getObject().getItem() instanceof ItemGun) {
			
			event.addCapability(new ResourceLocation("gunmod", "guninfo" + capid++), new GunInfoProvider());
		}
	}
	
}

 

And here is where I register the capability:

    private void setup(final FMLCommonSetupEvent event)
    {
        CapabilityManager.INSTANCE.register(GunInfo.class, new GunInfoStorage(), GunInfoProvider::new);
    }

 

Link to comment
Share on other sites

Howdy

Your code looks right on a quick read through

 

Try putting a breakpoint into both

ItemStack::
private void forgeInit() {

and

ItemStack::deserializeNBT

 

That should show you whether the capabilities are being constructed, serialised and deserialised properly.

 

I have a working tutorial example here

https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe32_inventory_item

But I don't see any significant difference between yours and mine.

 

-TGG

Link to comment
Share on other sites

Thank you for the help, I will make sure to check out your example. Unfortunately I solved the problem sometime yesterday. I don't know if this is the appropriate fix but it works for anyone else who might have the same issue:

 

In the provider class I have an ItemStack variable that is the Stack that the capability is affecting, and In the serializeNBT method I make sure to add the capability tags to the ItemStack like so:

	@Override
	public INBT serializeNBT() {
		INBT nbt = guninfo.getStorage().writeNBT(guninfo, this.instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")), null);
		if(owner.hasTag()) {
			owner.getTag().merge((CompoundNBT)nbt);
		} else {
			owner.setTag((CompoundNBT)nbt);
		}
		
		return nbt;
	}

 

This causes both NBT functions to be called correctly.

Link to comment
Share on other sites

3 hours ago, diesieben07 said:

This is completely broken. You must register your capability under the same name every time, because otherwise it obviously won't load correctly next time (because Forge now thinks it is a different capability).

Alright, thanks for the clarification. I wasn't sure from the Capability docs whether it was each instance must have a different name, or each custom capability registered must have a different name.

Link to comment
Share on other sites

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.



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Click Here -- Official Website -- Order Now ➡️● For Order Official Website - https://sale365day.com/get-restore-cbd-gummies ➡️● Item Name: — Restore CBD Gummies ➡️● Ingredients: — All Natural ➡️● Incidental Effects: — NA ➡️● Accessibility: — Online ✅HUGE DISCOUNT ! HURRY UP! ORDER NOW!✅ ✅HUGE DISCOUNT ! HURRY UP! ORDER NOW!✅ ✅HUGE DISCOUNT ! HURRY UP! ORDER NOW!✅   Restore CBD Gummies is a strong contender for the top gummy of the year. Due to its strong concentration of CBD and purity, you will achieve excellent results while using it if you stick with this solution. Most people who suffer from constant pain, anxiety, depression, and insomnia are currently solving these problems, and you can be the next one. All you need to do is give Restore CBD Gummies a chance and let this fantastic product change your life. Visit the official website to order your Restore CBD Gummies today! After reading Restore CBD Gummies reviews, we now know that knee replacement surgeries are not the only option to treat knee pain, inflammation, joint discomfort, and stiffness. These CBD gummies can heal your joints and provide you relief from pain and stress so that you can lead a happy life. Prosper Wellness Restore CBD Gummies can improve joint mobility and improve knee health so that you can remain healthy. Exclusive Details: *Restore CBD Gummies* Read More Details on Official Website #USA! https://www.facebook.com/claritox.pro.unitedstates https://www.facebook.com/illudermaUCAAU https://www.facebook.com/awakenxtusa https://groups.google.com/a/chromium.org/g/chromium-reviews/c/8NMUVKgd-FA https://groups.google.com/g/microsoft.public.project/c/0UZQQKOZF58 https://groups.google.com/g/comp.editors/c/r_BcRRrvGhs https://medium.com/@illuderma/illuderma-reviews-fda-approved-breakthrough-or-clever-skincare-scam-36088ae82c3e https://medium.com/@claritoxpros/claritox-pro-reviews-legitimate-or-deceptive-dr-warns-of-potential-dangers-d5ff3867b34d https://medium.com/@thedetoxall17/detoxall-17-reviews-scam-alert-or-legit-detox-solution-customer-report-inside-1fd4c6920c9e https://groups.google.com/a/chromium.org/g/chromium-reviews/c/RONgLAl6vwM https://groups.google.com/g/microsoft.public.project/c/TgtOMRFt6nQ https://groups.google.com/g/comp.editors/c/fUfg0L2YfzU https://crediblehealths.blogspot.com/2023/12/revitalize-with-restore-cbd-gummies.html https://community.weddingwire.in/forum/restore-cbd-gummies-uncovered-fda-approved-breakthrough-or-deceptive-wellness-scam--t206896 https://restorecbdgummies.bandcamp.com/album/restore-cbd-gummies-uncovered-fda-approved https://my-restore-cb.clubeo.com/page/restore-cbd-gummies-reviews-customer-alert-drs-warning-genuine-or-wellness-hoax.html https://my-restore-cb.clubeo.com/page/restore-cbd-gummies-reviews-scam-alert-or-legit-relief-solution-customer-report-inside.html https://medium.com/@restorecbdgum/restore-cbd-gummies-reviews-warning-2023-update-real-or-a-powerful-relief-hoax-caution-350b61472a3f https://devfolio.co/@restorecbdgum https://restore-cbd-gummies-9.jimdosite.com/ https://devfolio.co/project/new/restore-cbd-gummies-reviews-scam-or-legit-custo-7bd6 https://groups.google.com/a/chromium.org/g/chromium-reviews/c/R0enUCvfs8s https://groups.google.com/g/microsoft.public.project/c/miJma2yOMDQ https://groups.google.com/g/comp.os.vms/c/S_HG94aaKFo https://groups.google.com/g/mozilla.dev.platform/c/qb6WpMUYLu0 https://hellobiz.in/restore-cbd-gummies-reviews-warning-2023-update-genuine-wellness-or-another-hoax-caution-211948390 https://pdfhost.io/v/ir5l.cseV_Restore_CBD_Gummies_Reviews_WARNING_2023_Update_Genuine_Wellness_or_Another_Hoax_Caution https://odoe.powerappsportals.us/en-US/forums/general-discussion/7c8b3f62-6d96-ee11-a81c-001dd8066f2b https://gamma.app/public/Restore-CBD-Gummies-ssh57nprs2l6xgq https://restorecbdgummies.quora.com/ https://www.facebook.com/RestoreCBDGummiesUS https://groups.google.com/g/restorecbdgum/c/9KHVNp3oy3E https://sites.google.com/view/restorecbdgummiesreviewsfdaapp/home https://experiment.com/projects/pjyhtzvpcvllopsglcph/methods https://lookerstudio.google.com/reporting/e5e9f52d-ae52-4c84-96c6-96b97932215f/page/XtkkD https://restore-cbd-gummies-reviews-is-it-a-sca.webflow.io/ https://colab.research.google.com/drive/1xZoc6E2H-jliBSZRVl0vnVqrkc3ix4YU https://soundcloud.com/restore-cbd-gummies-821066674/restore-cbd-gummies https://www.eventcreate.com/e/restore-cbd-gummies-reviews https://restorecbdgummies.godaddysites.com/ https://sketchfab.com/3d-models/restore-cbd-gummies-reviews-fda-approved-7cfe1fb8b003481c81689dd9489d2812 https://www.scoop.it/topic/restore-cbd-gummies-by-restore-cbd-gummies-9 https://events.humanitix.com/restore-cbd-gummies https://communityforums.atmeta.com/t5/General-Development/Restore-CBD-Gummies/m-p/1113602
    • Click Here -- Official Website -- Order Now ➡️● For Order Official Website - https://sale365day.com/get-restore-cbd-gummies ➡️● Item Name: — Restore CBD Gummies ➡️● Ingredients: — All Natural ➡️● Incidental Effects: — NA ➡️● Accessibility: — Online ✅HUGE DISCOUNT ! HURRY UP! ORDER NOW!✅ ✅HUGE DISCOUNT ! HURRY UP! ORDER NOW!✅ ✅HUGE DISCOUNT ! HURRY UP! ORDER NOW!✅   Restore CBD Gummies is a strong contender for the top gummy of the year. Due to its strong concentration of CBD and purity, you will achieve excellent results while using it if you stick with this solution. Most people who suffer from constant pain, anxiety, depression, and insomnia are currently solving these problems, and you can be the next one. All you need to do is give Restore CBD Gummies a chance and let this fantastic product change your life. Visit the official website to order your Restore CBD Gummies today! After reading Restore CBD Gummies reviews, we now know that knee replacement surgeries are not the only option to treat knee pain, inflammation, joint discomfort, and stiffness. These CBD gummies can heal your joints and provide you relief from pain and stress so that you can lead a happy life. Prosper Wellness Restore CBD Gummies can improve joint mobility and improve knee health so that you can remain healthy. Exclusive Details: *Restore CBD Gummies* Read More Details on Official Website #USA! https://www.facebook.com/claritox.pro.unitedstates https://www.facebook.com/illudermaUCAAU https://www.facebook.com/awakenxtusa https://groups.google.com/a/chromium.org/g/chromium-reviews/c/8NMUVKgd-FA https://groups.google.com/g/microsoft.public.project/c/0UZQQKOZF58 https://groups.google.com/g/comp.editors/c/r_BcRRrvGhs https://medium.com/@illuderma/illuderma-reviews-fda-approved-breakthrough-or-clever-skincare-scam-36088ae82c3e https://medium.com/@claritoxpros/claritox-pro-reviews-legitimate-or-deceptive-dr-warns-of-potential-dangers-d5ff3867b34d https://medium.com/@thedetoxall17/detoxall-17-reviews-scam-alert-or-legit-detox-solution-customer-report-inside-1fd4c6920c9e https://groups.google.com/a/chromium.org/g/chromium-reviews/c/RONgLAl6vwM https://groups.google.com/g/microsoft.public.project/c/TgtOMRFt6nQ https://groups.google.com/g/comp.editors/c/fUfg0L2YfzU https://crediblehealths.blogspot.com/2023/12/revitalize-with-restore-cbd-gummies.html https://community.weddingwire.in/forum/restore-cbd-gummies-uncovered-fda-approved-breakthrough-or-deceptive-wellness-scam--t206896 https://restorecbdgummies.bandcamp.com/album/restore-cbd-gummies-uncovered-fda-approved https://my-restore-cb.clubeo.com/page/restore-cbd-gummies-reviews-customer-alert-drs-warning-genuine-or-wellness-hoax.html https://my-restore-cb.clubeo.com/page/restore-cbd-gummies-reviews-scam-alert-or-legit-relief-solution-customer-report-inside.html https://medium.com/@restorecbdgum/restore-cbd-gummies-reviews-warning-2023-update-real-or-a-powerful-relief-hoax-caution-350b61472a3f https://devfolio.co/@restorecbdgum https://restore-cbd-gummies-9.jimdosite.com/ https://devfolio.co/project/new/restore-cbd-gummies-reviews-scam-or-legit-custo-7bd6 https://groups.google.com/a/chromium.org/g/chromium-reviews/c/R0enUCvfs8s https://groups.google.com/g/microsoft.public.project/c/miJma2yOMDQ https://groups.google.com/g/comp.os.vms/c/S_HG94aaKFo https://groups.google.com/g/mozilla.dev.platform/c/qb6WpMUYLu0 https://hellobiz.in/restore-cbd-gummies-reviews-warning-2023-update-genuine-wellness-or-another-hoax-caution-211948390 https://pdfhost.io/v/ir5l.cseV_Restore_CBD_Gummies_Reviews_WARNING_2023_Update_Genuine_Wellness_or_Another_Hoax_Caution https://odoe.powerappsportals.us/en-US/forums/general-discussion/7c8b3f62-6d96-ee11-a81c-001dd8066f2b https://gamma.app/public/Restore-CBD-Gummies-ssh57nprs2l6xgq https://restorecbdgummies.quora.com/ https://www.facebook.com/RestoreCBDGummiesUS https://groups.google.com/g/restorecbdgum/c/9KHVNp3oy3E https://sites.google.com/view/restorecbdgummiesreviewsfdaapp/home https://experiment.com/projects/pjyhtzvpcvllopsglcph/methods https://lookerstudio.google.com/reporting/e5e9f52d-ae52-4c84-96c6-96b97932215f/page/XtkkD https://restore-cbd-gummies-reviews-is-it-a-sca.webflow.io/ https://colab.research.google.com/drive/1xZoc6E2H-jliBSZRVl0vnVqrkc3ix4YU https://soundcloud.com/restore-cbd-gummies-821066674/restore-cbd-gummies https://www.eventcreate.com/e/restore-cbd-gummies-reviews https://restorecbdgummies.godaddysites.com/ https://sketchfab.com/3d-models/restore-cbd-gummies-reviews-fda-approved-7cfe1fb8b003481c81689dd9489d2812 https://www.scoop.it/topic/restore-cbd-gummies-by-restore-cbd-gummies-9 https://events.humanitix.com/restore-cbd-gummies https://communityforums.atmeta.com/t5/General-Development/Restore-CBD-Gummies/m-p/1113602
    • i use fabric 1.20.1 i used alot of mods like all the trims, bobby, better stats, and more but i encounter a problem when i try to enter my world it force me to be in safe mode and when i click on safe mode it just crash minecraft
    • Dr Oz Bites CBD Gummies: As the manufacturer isn't certain about the end result of the supplement, they are going at the back of faux paid promotions to growth the call for for the product. I felt that it's miles because of this motive, Dr Oz Bites CBD Gummies is earning a variety of popularity among the populace.   ➥ ✅Official Website: https://gummiestoday.com/Dr-Oz-Bites-CBD-Gummies/ ➥ Product Name: Dr Oz Bites CBD Gummies ➥ Benefits: Dr Oz Bites CBD Gummies Helps you to get Pain Relief ➥ Healthy Benefits :Control your hormone levels ➥ Category:Pain Relief Supplement ➥ Rating: ★★★★☆ (4.5/5.0) ➥ Side Effects: No Major Side Effects ➥ Availability: In Stock Voted #1 Product in the United States   📞📞 ✔Hurry Up🤑CLICK HERE TO BUY – “OFFICIAL WEBSITE”🎊👇〽💝💞❣️ 📞📞 ✔Hurry Up🤑CLICK HERE TO BUY – “OFFICIAL WEBSITE”🎊👇〽💝💞❣️ 📞📞 ✔Hurry Up🤑CLICK HERE TO BUY – “OFFICIAL WEBSITE”🎊👇〽💝💞❣️     FOR MORE INFO VISIT OUR OTHER LINKS :- https://www.onlymyhealth.com/dr-oz-cbd-gummies-reviews-care-cbd-shark-tank-gummies-exposed-benefits-1701579520 https://www.deccanherald.com/brandspot/featured/cbd-dr-oz-gummies-reviews-care-cbd-gummies-2023-dr-oz-gummies-is-it-worth-buying-2-2797780 https://www.onlymyhealth.com/cbd-dr-oz-gummies-diabetes-reviews-dr-oz-shark-tank-cbd-gummies-1702083884   Official Facebook Page:- https://www.facebook.com/GreenVibeCBDGummiesForDiabetes https://www.facebook.com/DrOzBitesCBDGummiesSupplement   FOR MORE INFO VISIT OUR OFFICIAL SITE :- https://groups.google.com/g/drone-dev-platform/c/X-xNP-OefLg https://groups.google.com/g/mozilla.dev.platform/c/i9X2WfOmkUs https://groups.google.com/g/mozilla.dev.platform/c/DP8vaQGqayk https://groups.google.com/g/comp.os.vms/c/V9XrF_T5u08 https://groups.google.com/g/comp.mobile.android/c/XuYes3irk9w https://groups.google.com/a/chromium.org/g/chromium-reviews/c/xCJCm9yhigE https://groups.google.com/g/comp.protocols.time.ntp/c/yErPa0A9uw0 https://groups.google.com/g/mozilla.dev.platform/c/dzcLb8COWts   Other Reference Pages JIMDO@ https://dr-oz-b-i-t-e-s-cbd-gummies.jimdosite.com/ GROUP GOOGLE@ https://groups.google.com/g/dr-oz-bites-cbd-gummies-lifestyle/c/MTpEvLDAPb0 GOOGLE SITE@ https://sites.google.com/view/drozbitescbdgummiesingredients/ GAMMA APP@ https://gamma.app/docs/Dr-Oz-Bites-CBD-GummiesIS-FAKE-or-REAL-Read-About-100-Natural-Pro-z7obrrpiq9agw3v Company sites@ https://dr-oz-bites-cbd-gummies-side-effects.company.site/   Recent Searches:- #DrOzBitesCBDGummiesReviews #DrOzBitesCBDGummiesLifestyle #DrOzBitesCBDGummiesBenefits #DrOzBitesCBDGummiesBuy #DrOzBitesCBDGummiesCost #DrOzBitesCBDGummiesIngredients #DrOzBitesCBDGummiesOrder #DrOzBitesCBDGummiesPrice #DrOzBitesCBDGummiesWebsite #DrOzBitesCBDGummiesResults #DrOzBitesCBDGummiesSideEffects #DrOzBitesCBDGummiesAdvantage #DrOzBitesCBDGummiesOffers #DrOzBitesCBDGummiesSupplement #DrOzBitesCBDGummiesBuyNow #DrOzBitesCBDGummiesFormula #DrOzBitesCBDGummiesHowToUse Our Official Blog Link Below:- BLOGSPOT==>>https://dr-oz-bites-cbd-gummies-advantage.blogspot.com/2023/12/Dr-Oz-Bites-CBD-Gummies.html Sunflower==>>https://www.sunflower-cissp.com/glossary/cissp/7068/dr-oz-bites-cbd-gummies-reviews-dr-oz-bites-cbd-gummies-where-to-buy Lawfully ==>>https://www.lawfully.com/community/posts/dr-oz-bites-cbd-gummies-navigating-the-wellness-landscape-BYTaVtWKNIUrHsIxGaivMA%3D%3D DIBIZ==>>https://www.dibiz.com/morrislymorales   Medium==>>https://medium.com/@elizabekennedy/is-dr-oz-bites-cbd-gummies-brand-legit-34cfcab397be   Devfolio==>>https://devfolio.co/projects/how-many-dr-oz-bites-cbd-gummies-need-to-i-take-cdf6        
  • Topics

×
×
  • Create New...

Important Information

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