Jump to content

[Solved][1.16.5] Issue with Capability Values


MonkeyKnight

Recommended Posts

I have successfully created a capability value which stores if a player has a disease. While to code runs with no errors, I have run into difficulties with storing the value and using it in my code. I have created an event which triggered on each tick. After a random number of ticks, if the diseases value in my capability is zero, it changes it to one and the player becomes sick. I outputted the value of diseases on every tick to help me debug. Looking at my print statements, after becoming sick it outputs mostly ones, but continues outputting zeros sometimes. Additionally, when the game is exited and returned to, the values go back to being all zeros. I cannot find my error. Is my capability storing values correctly?

My Event code:

@EventBusSubscriber(modid = Epidemics.MOD_ID, bus = Bus.FORGE)
public class DiseaseStartEvents {
	@SubscribeEvent
	public static void onPlayerTick(PlayerTickEvent event)
	{
		Random rand = new Random();
		int i = rand.nextInt(800);
		System.out.println(DiseaseStats.getSickness(event.player));
		if(i == 2 && DiseaseStats.getSickness(event.player) == 0)
		{
			ITextComponent m = new StringTextComponent("You have fallen ill...");
			event.player.sendMessage(m, event.player.getGameProfile().getId());
			DiseaseStats.setSickness(1, event.player);	
		}
	}
}

The Class I have been using to access the capability (I know it is a bit sketchy...):

public class DiseaseStats {
	public static void setSickness(int i, PlayerEntity player)
	{
		player.getCapability(DiseasesProvider.DISEASES_CAPABILITY).ifPresent(new NonNullConsumer<IDiseases>() {

			@Override
			public void accept(IDiseases t) {
				t.setDiseases(i);
			}
		});
	}
	static int i = -1;
	public static int getSickness(PlayerEntity player)
	{
		player.getCapability(DiseasesProvider.DISEASES_CAPABILITY).ifPresent(new NonNullConsumer<IDiseases>() {

			@Override
			public void accept(IDiseases t) {
				i = t.getDiseases();
			}
		});
		return i;
	}
}

My print out:

[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Render thread/INFO] [minecraft/NewChatGui]: [CHAT] You have fallen ill...
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1
[10:21:21] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1
[10:21:21] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1
[10:21:21] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1
[10:21:21] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 0
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1
[10:21:21] [Render thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:21]: 1

My Capability code is here (The only thing different from that code and my current code is that I fixed the event bus error): 

Do you know what I am doing wrong?

 

Edited by MonkeyKnight
Solved
Link to comment
Share on other sites

Thanks, now it works perfectly. To anyone else who may have the same problem as me in the future, I changed the event to this:

@EventBusSubscriber(modid = Epidemics.MOD_ID, bus = Bus.FORGE)
public class DiseaseStartEvents {
	
	@SubscribeEvent
	public static void onPlayerTick(PlayerTickEvent event)
	{
		if(event.side == LogicalSide.SERVER && event.phase == Phase.START)
		{
			Random rand = new Random();
			int i = rand.nextInt(800);
			System.out.println(DiseaseStats.getSickness(event.player));
			if(i == 2 && DiseaseStats.getSickness(event.player) == 0)
			{
				ITextComponent m = new StringTextComponent("You have fallen ill...");
				event.player.sendMessage(m, event.player.getGameProfile().getId());
				DiseaseStats.setSickness(1, event.player);	
			}
		}
	}
}

 

Link to comment
Share on other sites

  • MonkeyKnight changed the title to [1.16.5] Issue with Capability Values

For saving the Capability, I have looked at the documentation and some forum posts as well but still cannot figure out what classes to use. I want my capability to reset upon player death so I never used the playerClone event. All I am trying to do is to save and load my capability when changing dimensions and leaving and rejoining a world. Other than that though, my Capability works like a charm!

Link to comment
Share on other sites

 

I have already added a ICapabilitySerializable. It still does not save any data. I am not getting any errors in my Capability as it works as intended each time, except that it resets after leaving and reentering the world. Is there something wrong with my class? 

public class DiseasesProvider implements ICapabilitySerializable<INBT> {

	@CapabilityInject(IDiseases.class)
	public static final Capability<IDiseases> DISEASES_CAPABILITY = null;

	private LazyOptional<IDiseases> instance = LazyOptional.of(DISEASES_CAPABILITY::getDefaultInstance);

	@Override
	public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
		return cap == DISEASES_CAPABILITY ? instance.cast() : LazyOptional.empty();
	}

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

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

 

Here is my AttachCapabilitiesEvent:

	@SubscribeEvent
	public static void onAttachCapabilities(AttachCapabilitiesEvent<Entity> event) {
		if (event.getObject() instanceof PlayerEntity) {
			event.addCapability(new ResourceLocation(Epidemics.MOD_ID, "diseases"), new DiseasesProvider());
		}
	}

 

Edited by MonkeyKnight
Link to comment
Share on other sites

I am not too familiar with the eclipse debugger, (The last time I modded was on 1.7.10 using Intellij). I know that my getCapability() method is working, but after adding print statements to the  serializeNBT and deserializeNBT, I did not see any printouts so I do not believe they have been invoked.

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

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

I am 99% sure they are doing the right thing because it is nearly the same as what I have found in the Minecraft forge code and seen on this forum. I am not sure that I am checking to see if the data is present. Is there some code that I am missing? Not sure if this helps but here is my Read and Write NBT code:

public class DiseasesStorage implements IStorage<IDiseases>{

	@Override
	public INBT writeNBT(Capability<IDiseases> capability, IDiseases instance, Direction side) {
		CompoundNBT tag = new CompoundNBT();
		tag.putInt("diseases", instance.getDiseases());
		tag.putInt("diseasesTime", instance.getDiseasesTime());
		return tag;
	}

	@Override
	public void readNBT(Capability<IDiseases> capability, IDiseases instance, Direction side, INBT nbt) {
		CompoundNBT tag = new CompoundNBT();
		instance.setDiseases(tag.getInt("diseases"));
		instance.setDiseases(tag.getInt("diseasesTime"));
	}

}

 

Link to comment
Share on other sites

I have done some further testing and have noticed something quite strange. I have changed my readNBT method to read from the INBT.

	@Override
	public INBT writeNBT(Capability<IDiseases> capability, IDiseases instance, Direction side) {
		CompoundNBT tag = new CompoundNBT();
		tag.putInt("diseases", instance.getDiseases());
		tag.putInt("diseasesTime", instance.getDiseasesTime());
		return tag;
	}

	@Override
	public void readNBT(Capability<IDiseases> capability, IDiseases instance, Direction side, INBT nbt) {
		CompoundNBT tag = (CompoundNBT) nbt;
		instance.setDiseases(tag.getInt("diseases"));
		instance.setDiseases(tag.getInt("diseasesTime"));
	}

The interesting thing that I noticed when testing after making the change is that the Serialize method is called twice when leaving a world an the reserialize method is called once when rejoining. My Capacity stores two ints called diseases and diseaseTime. However, when I exit and reload a world, the diseaseTime value becomes the dseases value. Here is the printout from my test where a world with a diseases value of 1 and a diseaseTime value of 2331 is exited and reentered.

// After leaving and entering the world, as the world is loaded the Capacity is deserialized once.

[18:57:51] [Netty Server IO #3/DEBUG] [ne.mi.fm.ne.FMLHandshakeHandler/FMLHANDSHAKE]: Received client indexed reply 1 of type net.minecraftforge.fml.network.FMLHandshakeMessages$C2SAcknowledge
[18:57:51] [Netty Server IO #3/DEBUG] [ne.mi.fm.ne.FMLHandshakeHandler/FMLHANDSHAKE]: Received acknowledgement from client
[18:57:51] [Server thread/DEBUG] [ne.mi.fm.ne.FMLHandshakeHandler/FMLHANDSHAKE]: Handshake complete!
[18:57:51] [Netty Local Client IO #1/INFO] [ne.mi.fm.ne.NetworkHooks/]: Connected to a modded server.
[18:57:51] [Server thread/INFO] [ne.mi.co.AdvancementLoadFix/]: Using new advancement loading for net.minecraft.advancements.PlayerAdvancements@5772ea3a
[18:57:51] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.capabilities.DiseasesProvider:deserializeNBT:32]: deserialize diseases
[18:57:51] [Server thread/INFO] [minecraft/PlayerList]: Dev[local:E:0daae43a] logged in with entity id 733 at (-170.35850493023133, 71.0, 129.3425231398343)
[18:57:51] [Server thread/INFO] [minecraft/MinecraftServer]: Dev joined the game

//When the world is rejoined the diseaseTime int becomes the disease int, breaking my code

[18:57:52] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:26]: 2331
[18:57:52] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:26]: 2331
[18:57:52] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:26]: 2331
[18:57:52] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:26]: 2331
[18:57:52] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.events.DiseaseStartEvents:onPlayerTick:26]: 2331
[18:57:52] [Server thread/INFO] [minecraft/IntegratedServer]: Saving and pausing game...

//When the game saves and exits the world, the Capability is Serialized twice

[18:57:52] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.capabilities.DiseasesProvider:serializeNBT:26]: serialize diseases
[18:57:52] [Server thread/INFO] [STDOUT/]: [com.monkey.epidemics.capabilities.DiseasesProvider:serializeNBT:26]: serialize diseases
[18:57:52] [Server thread/INFO] [minecraft/MinecraftServer]: Saving chunks for level 'ServerLevel[New World]'/minecraft:overworld
[18:57:53] [Render thread/INFO] [minecraft/AdvancementList]: Loaded 0 advancements
[18:57:53] [Server thread/INFO] [minecraft/MinecraftServer]: Saving chunks for level 'ServerLevel[New World]'/minecraft:the_nether
[18:57:53] [Server thread/INFO] [minecraft/MinecraftServer]: Saving chunks for level 'ServerLevel[New World]'/minecraft:the_end

Is SerializeNBT being called twice causing this error? Is this duplication caused by some kind of server client thing? If that is the case is there some way I should make it server only?

Link to comment
Share on other sites

I have solved the issue as I called the wrong method in the ReadNBT class. Here is my final updated code.

	@Override
	public INBT writeNBT(Capability<IDiseases> capability, IDiseases instance, Direction side) {
		CompoundNBT tag = new CompoundNBT();
		tag.putInt("diseases", instance.getDiseases());
		tag.putInt("diseasesTime", instance.getDiseasesTime());
		return tag;
	}

	@Override
	public void readNBT(Capability<IDiseases> capability, IDiseases instance, Direction side, INBT nbt) {
		CompoundNBT tag = (CompoundNBT) nbt;
		instance.setDiseases(tag.getInt("diseases"));
		instance.setDiseasesTime(tag.getInt("diseasesTime"));
	}

 

Link to comment
Share on other sites

  • MonkeyKnight changed the title to [Solved][1.16.5] Issue with Capability Values

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

    • I have done this now but have got the error:   'food(net.minecraft.world.food.FoodProperties)' in 'net.minecraft.world.item.Item.Properties' cannot be applied to                '(net.minecraftforge.registries.RegistryObject<net.minecraft.world.item.Item>)' public static final RegistryObject<Item> LEMON_JUICE = ITEMS.register( "lemon_juice", () -> new Item( new HoneyBottleItem.Properties().stacksTo(1).food( (new FoodProperties.Builder()) .nutrition(3) .saturationMod(0.25F) .effect(() -> new MobEffectInstance(MobEffects.DAMAGE_RESISTANCE, 1500), 0.01f ) .build() ) )); The code above is from the ModFoods class, the one below from the ModItems class. public static final RegistryObject<Item> LEMON_JUICE = ITEMS.register("lemon_juice", () -> new Item(new Item.Properties().food(ModFoods.LEMON_JUICE)));   I shall keep going between them to try and figure out the cause. I am sorry if this is too much for you to help with, though I thank you greatly for your patience and all the effort you have put in to help me.
    • I have been following these exact tutorials for quite a while, I must agree that they are amazing and easy to follow. I have registered the item in the ModFoods class, I tried to do it in ModItems (Where all the items should be registered) but got errors, I think I may need to revert this and figure it out from there. Once again, thank you for your help! 👍 Just looking back, I have noticed in your code you added ITEMS.register, which I am guessing means that they are being registered in ModFoods, I shall go through the process of trial and error to figure this out.
    • ♈+2349027025197ஜ Are you a pastor, business man or woman, politician, civil engineer, civil servant, security officer, entrepreneur, Job seeker, poor or rich Seeking how to join a brotherhood for protection and wealth here’s is your opportunity, but you should know there’s no ritual without repercussions but with the right guidance and support from this great temple your destiny is certain to be changed for the better and equally protected depending if you’re destined for greatness Call now for enquiry +2349027025197☎+2349027025197₩™ I want to join ILLUMINATI occult without human sacrificeGREATORLDRADO BROTHERHOOD OCCULT , Is The Club of the Riches and Famous; is the world oldest and largest fraternity made up of 3 Millions Members. We are one Family under one father who is the Supreme Being. In Greatorldrado BROTHERHOOD we believe that we were born in paradise and no member should struggle in this world. Hence all our new members are given Money Rewards once they join in order to upgrade their lifestyle.; interested viewers should contact us; on. +2349027025197 ۝ஐℰ+2349027025197 ₩Greatorldrado BROTHERHOOD OCCULT IS A SACRED FRATERNITY WITH A GRAND LODGE TEMPLE SITUATED IN G.R.A PHASE 1 PORT HARCOURT NIGERIA, OUR NUMBER ONE OBLIGATION IS TO MAKE EVERY INITIATE MEMBER HERE RICH AND FAMOUS IN OTHER RISE THE POWERS OF GUARDIANS OF AGE+. +2349027025197   SEARCHING ON HOW TO JOIN THE Greatorldrado BROTHERHOOD MONEY RITUAL OCCULT IS NOT THE PROBLEM BUT MAKE SURE YOU'VE THOUGHT ABOUT IT VERY WELL BEFORE REACHING US HERE BECAUSE NOT EVERYONE HAS THE HEART TO DO WHAT IT TAKES TO BECOME ONE OF US HERE, BUT IF YOU THINK YOU'RE SERIOUS MINDED AND READY TO RUN THE SPIRITUAL RACE OF LIFE IN OTHER TO ACQUIRE ALL YOU NEED HERE ON EARTH CONTACT SPIRITUAL GRANDMASTER NOW FOR INQUIRY +2349027025197   +2349027025197 Are you a pastor, business man or woman, politician, civil engineer, civil servant, security officer, entrepreneur, Job seeker, poor or rich Seeking how to join
    • Hi, I'm trying to use datagen to create json files in my own mod. This is my ModRecipeProvider class. public class ModRecipeProvider extends RecipeProvider implements IConditionBuilder { public ModRecipeProvider(PackOutput pOutput) { super(pOutput); } @Override protected void buildRecipes(Consumer<FinishedRecipe> pWriter) { ShapedRecipeBuilder.shaped(RecipeCategory.MISC, ModBlocks.COMPRESSED_DIAMOND_BLOCK.get()) .pattern("SSS") .pattern("SSS") .pattern("SSS") .define('S', ModItems.COMPRESSED_DIAMOND.get()) .unlockedBy(getHasName(ModItems.COMPRESSED_DIAMOND.get()), has(ModItems.COMPRESSED_DIAMOND.get())) .save(pWriter); ShapelessRecipeBuilder.shapeless(RecipeCategory.MISC, ModItems.COMPRESSED_DIAMOND.get(),9) .requires(ModBlocks.COMPRESSED_DIAMOND_BLOCK.get()) .unlockedBy(getHasName(ModBlocks.COMPRESSED_DIAMOND_BLOCK.get()), has(ModBlocks.COMPRESSED_DIAMOND_BLOCK.get())) .save(pWriter); ShapedRecipeBuilder.shaped(RecipeCategory.MISC, ModItems.COMPRESSED_DIAMOND.get()) .pattern("SSS") .pattern("SSS") .pattern("SSS") .define('S', Blocks.DIAMOND_BLOCK) .unlockedBy(getHasName(ModItems.COMPRESSED_DIAMOND.get()), has(ModItems.COMPRESSED_DIAMOND.get())) .save(pWriter); } } When I try to run the runData client, it shows an error:  Caused by: java.lang.IllegalStateException: Duplicate recipe compressed:compressed_diamond I know that it's caused by the fact that there are two recipes for the ModItems.COMPRESSED_DIAMOND. But I need both of these recipes, because I need a way to craft ModItems.COMPRESSED_DIAMOND_BLOCK and restore 9 diamond blocks from ModItems.COMPRESSED_DIAMOND. Is there a way to solve this?
  • Topics

×
×
  • Create New...

Important Information

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