Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

[Solved][1.16.5] Issue with Capability Values


Recommended Posts

Posted (edited)

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 post
Share on other sites
  • PlayerTickEvent runs on server and client. You should do this stuff only on the server. You can see this in the log by noticing that two threads are printing the value (server and client thread).
  • PlayerTickEvent (like all tick events) runs twice every tick, check TickEvent#phase.
  • Unless your capability really is optional (you only sometimes add it), ifPresent is the wrong tool to use. Use orElseThrow to indicate the absence as a fatal error.
  • To know why your data does not save you'd have to show the code that actually does the saving.
Link to post
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 post
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 post
Share on other sites

For attached capabilities (using AttachCapabilityEvent) the ICapabilityProvider you attach must implement INBTSerializable (you can use ICapabilitySerializable which combines both interfaces). It is then queried when the object you attach to (the player in this case) is saved and you can save any additional data.

Link to post
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 post
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 post
Share on other sites

You have reported "the data is no longer there after a world reload". How have you determined this?

Your read code does precisely nothing. It completely ignores the NBT data it is given. Instead it creates an empty NBT tag and then attempts to read values from it. Those values will always be 0.

Link to post
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 post
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 post
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.

Guest
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

    • I have made a custom armor piece and have given it a texture for when you hold it. I have also made a custom armor material but I dont know how to make it so that when you where the armor you see a custom texture.
    • Probably only the main block should hold all the data, that way you don't have things spread out.
    • It hasn't been changed in a long time and should be updated.  But no, it's not overly aggressive. People don't read it. Look at all the support threads. 90% of them are "okay i have this issue", no debug.log in sight.
    • I solved it by copying the .gradle folder from another laptop where it works to run the client!
    • I am currently drawing a compass to my ingame gui as follows: private static void renderCompass(MatrixStack matrixStack, int width, int height) { TextureDrawer.drawGuiTexture(matrixStack, width / 2 - 110, 10, 0, 37, 221, 14); int rot; boolean f0 = mc.player.yRot < 0.0f; if(f0) rot = -MathHelper.floor(mc.player.yRot % 360); else rot = MathHelper.floor(mc.player.yRot % 360); boolean f1 = rot > 0 && rot < 180; boolean f2 = rot <= 270 && rot >= 90; boolean f3 = rot <= 180 && rot >= 0; AtomicInteger targetAngle = new AtomicInteger(-1); mc.player.getCapability(ISkyrimPlayerDataProvider.SKYRIM_PLAYER_DATA_CAPABILITY).ifPresent(cap -> { if(cap.getCurrentTarget() != null && cap.getCurrentTarget().isAlive()) { Vector3d playerPos = mc.player.getLookAngle(); Vector3d targetPos = cap.getCurrentTarget().position(); Vector3d norm = playerPos.subtract(targetPos); double angleDir = (Math.atan2(norm.z, norm.x) / 2 / Math.PI * 360 + 360) % 360; double angleLook = (Math.atan2(playerPos.z, playerPos.x) / 2 / Math.PI * 360 + 360) % 360; targetAngle.set((int)(angleDir - angleLook + 360) % 360); } else targetAngle.set(-1); }); int targetEntityAngle = targetAngle.get(); if(targetEntityAngle > 0 && targetEntityAngle <= 90) TextureDrawer.drawGuiTexture(matrixStack, width / 2 - targetEntityAngle, 14, 105, 52, 6, 6); else if(targetEntityAngle > 90 && targetEntityAngle <= 180) TextureDrawer.drawGuiTexture(matrixStack, width / 2 - targetEntityAngle + 90, 14, 105, 52, 6, 6); if (rot == 0) { drawCenteredString(matrixStack, fontRenderer, "S", width / 2, 13, 16777215); drawCenteredString(matrixStack, fontRenderer, "E", (width / 2) - 90, 13, 16777215); drawCenteredString(matrixStack, fontRenderer, "W", (width / 2) + 90, 13, 16777215); } else if (!f0) { drawCenteredString(matrixStack, fontRenderer, f2 ? "N" : "", (width / 2 - rot) + 180, 13, 16777215); if (!f1) rot -= 360; drawCenteredString(matrixStack, fontRenderer, !f2 ? "S" : "", width / 2 - rot, 13, 16777215); drawCenteredString(matrixStack, fontRenderer, !f3 ? "E" : "", (width / 2 - rot) - 90, 13, 16777215); drawCenteredString(matrixStack, fontRenderer, f3 ? "W" : "", (width / 2 - rot) + 90, 13, 16777215); } else if(f0) { drawCenteredString(matrixStack, fontRenderer, f2 ? "N" : "", (width / 2 + rot) - 180, 13, 16777215); if (!f1) rot -= 360; drawCenteredString(matrixStack, fontRenderer, !f2 ? "S" : "", width / 2 + rot, 13, 16777215); drawCenteredString(matrixStack, fontRenderer, !f3 ? "W" : "", (width / 2 + rot) + 90, 13, 16777215); drawCenteredString(matrixStack, fontRenderer, f3 ? "E" : "", (width / 2 + rot) - 90, 13, 16777215); } } What I'm trying to do is only render the entity texture (the calls including targetEntityAngle) when it is in compass view.  
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

By using this site, you agree to our Privacy Policy.