Jump to content

[Solved] [1.16.1] Trouble with Capabilities and LazyOptionals


Recommended Posts

Posted (edited)

Hello,

For the mod I'm making, I need to store persistent data on the player (strength, intelligence, dexterity, etc) and from what I've been reading Capabilities seem to be the way to go. So I've created my own called PlayerData.

Here is the interface:

public interface IPlayerData {

    Capability<Optional<PlayerData>> getCapability();
    void setCapability(Capability<Optional<PlayerData>> capability);

    float getHealth();
    void setHealth(float amount);

    int getStrength();
    int getDexterity();
    int getIntelligence();

    void setStrength(int amount);
    void setDexterity(int amount);
    void setIntelligence(int amount);

    void addStrength(int amount);
    void addDexterity(int amount);
    void addIntelligence(int amount);
}

and here is the main class (The Storage part of it as well as NBT read/write is here too):

public class PlayerData implements IPlayerData, ICapabilitySerializable<CompoundNBT> {
    @CapabilityInject(IPlayerData.class)
    public static Capability<IPlayerData> INSTANCE = null;
    private final LazyOptional<IPlayerData> holder = LazyOptional.of(() -> {
        return this;
    });
    // private Capability<Optional<PlayerData>> storage = new Capability<>();

    private float health;
    private int strength;
    private int dexterity;
    private int intelligence;

    public PlayerData() {
    }

    @Override
    public Capability<Optional<PlayerData>> getCapability() {
        return null;
    }

    @Override
    public void setCapability(Capability<Optional<PlayerData>> capability) {

    }

    // I removed all the getters/setters so it wouldn't be so long

    @Nonnull @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        return INSTANCE.orEmpty(cap, this.holder);
    }

    @Override
    public CompoundNBT serializeNBT() {
        CompoundNBT nbt = new CompoundNBT();
        nbt.putFloat("Health", this.health);
        nbt.putInt("Strength", this.strength);
        nbt.putInt("Dexterity", this.dexterity);
        nbt.putInt("Intelligence", this.intelligence);
        return nbt;
    }

    @Override
    public void deserializeNBT(CompoundNBT nbt) {
        this.health = nbt.getFloat("Health");
        this.strength = nbt.getInt("Strength");
        this.dexterity = nbt.getInt("Dexterity");
        this.intelligence = nbt.getInt("Intelligence");
    }

    public static class Storage implements Capability.IStorage<IPlayerData> {
        public Storage() {
        }

        @Nullable @Override
        public INBT writeNBT(Capability<IPlayerData> capability, IPlayerData instance, Direction side) {
            return instance instanceof PlayerData ? ((PlayerData)instance).serializeNBT() : new CompoundNBT();
        }
        @Override
        public void readNBT(Capability<IPlayerData> capability, IPlayerData instance, Direction side, INBT nbt) {
            if (instance instanceof PlayerData) {
                ((PlayerData)instance).deserializeNBT((CompoundNBT)nbt);
            }

        }
    }

    public static void register() {
        CapabilityManager.INSTANCE.register(IPlayerData.class, new PlayerData.Storage(), PlayerData::new);
    }
}

(I also have a CapabilityHandler class that has the AttachCapabilitiesEvent<Entity> )

And the game launches fine, but for some reason I don't know how to access the actual data from the Capability I created. I don't know how to deal with a LazyOptional and there isn't much out there for help. I'm using this so far and it doesn't work:

LazyOptional<IPlayerData> data = player.getCapability(PlayerData.INSTANCE);
        data.ifPresent((test) -> {
            MajCraft.LOGGER.info("testing" + test);
        });

How do I use my Capability to get let's say the strength stat of the player? And why does the method in the lambda expression not fire? Thank you very much

Edited by majesity
The issue was solved
Posted
  On 7/23/2020 at 7:53 PM, majesity said:

How do I use my Capability to get let's say the strength stat of the player?

Expand  

test.getStrength()

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

That doesn't work, nothing prints on the log. Does this mean that there is no data attached to the player? Here's my CapabilityHandler class, maybe I did something wrong there?

@Mod.EventBusSubscriber(modid = MajCraft.MOD_ID, bus = Mod.EventBusSubscriber.Bus.FORGE)
public class CapabilityHandler {
    public static final ResourceLocation PLAYER_DATA = new ResourceLocation(MajCraft.MOD_ID, "playerdata");

    @SubscribeEvent
    public void attachCapability(AttachCapabilitiesEvent<Entity> event) {
        if(!(event.getObject() instanceof PlayerEntity)) {
            return; }
        event.addCapability(PLAYER_DATA, new PlayerData());
    }

}

How would I add data to the player? test.getStrength() doesn't work because I'm assuming there is no data in the first place.

Posted

By the way

  On 7/23/2020 at 7:53 PM, majesity said:

Capability<Optional<PlayerData>> getCapability();

void setCapability(Capability<Optional<PlayerData>> capability);

Expand  

These two methods on your capability make no sense. If you have the capability, getting a capability from it is nonsense (capabilities are not themselves capability providers, unless they are, in which case you would have to additionally extend that interface).

 

Anyway, I think your classes have gotten confused with each other in what each one's purpose is, so the thing you're attaching and trying to get back out isn't actually the same thing as the object you expect to hold the data. Or it isn't being attached, registered, or retrieved properly. Little unclear because you haven't shown where you're trying to get it at (you've shown the code you're using but not its enclosing scope).

 

Either way, I suggest taking a look at my code:
https://github.com/Draco18s/ReasonableRealism/blob/1.14.4/src/main/java/com/draco18s/hardlib/api/capability/CapabilityMechanicalPower.java

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

Does that mean I need to make another class that actually holds the data from the PlayerData capability? Here is the entire block of code I am trying to get the data:

@Mod.EventBusSubscriber(modid = MajCraft.MOD_ID, bus = Mod.EventBusSubscriber.Bus.FORGE, value = Dist.CLIENT)
public class ModClientEvents {

    @SubscribeEvent
    public static void onJump(LivingEvent.LivingJumpEvent event) {
        LivingEntity player = event.getEntityLiving();
         LazyOptional<IPlayerData> data = player.getCapability(PlayerData.INSTANCE);
        data.ifPresent((test) -> {
            MajCraft.LOGGER.info("testing " + test.getStrength());
        });

    }

How do I make sure the thing I am attaching is the same as the object holding the data? I have the IPlayerData interface to define the structure of the capability and then the PlayerData to create the default instance of it... what else do I need? And what Java concept do I need to teach myself to be able to understand this better, or is this just a Forge thing?

Posted

You've already attach the capability to all players (don't worry about who's going to be attached, it knows who's the saved data's owner). You can also use 

player.getCapability(PlayerData.INSTANCE).orElseThrow(...)

instead of 

ifPresent

since every player should have one.

Posted

The problem is neither of them are working, it doesn’t get the data because I’m doing something wrong. I don’t know what though. I’ve spent a very long time trying to figure out this capability thing.

Posted (edited)

Ok so I have completely changed around everything. I found another Forge topic and they had their Capabilities set up way more organized, so I mimicked theirs. I have the following:

Interface:

public interface IPlayerData {
    float getHealth();
    void setHealth(float amount);
    int getStrength();
    int getDexterity();
    int getIntelligence();
    void setStrength(int amount);
    void setDexterity(int amount);
    void setIntelligence(int amount);
    void addStrength(int amount);
    void addDexterity(int amount);
    void addIntelligence(int amount);
}

Factory:

public class PlayerDataFactory implements IPlayerData{
    private float health;
    private int strength;
    private int dexterity;
    private int intelligence;

    public PlayerDataFactory() {
    }

    @Override
    public float getHealth() {
        return health;
    }

    @Override
    public void setHealth(float amount) {
        this.health = amount;
    }

    @Override
    public int getStrength() {
        return strength;
    }

    @Override
    public int getDexterity() {
        return dexterity;
    }

    @Override
    public int getIntelligence() {
        return intelligence;
    }

    @Override
    public void setStrength(int amount) {
        this.strength = amount;
    }

    @Override
    public void setDexterity(int amount) {
        this.dexterity = amount;
    }

    @Override
    public void setIntelligence(int amount) {
        this.intelligence = amount;
    }

    @Override
    public void addStrength(int amount) {
        this.strength += amount;
    }

    @Override
    public void addDexterity(int amount) {
        this.dexterity += amount;
    }

    @Override
    public void addIntelligence(int amount) {
        this.intelligence += amount;
    }
}

Provider:

public class PlayerDataProvider implements ICapabilitySerializable<INBT> {
    @CapabilityInject(IPlayerData.class)
    public static Capability<IPlayerData> capability = null;
    private LazyOptional<IPlayerData> instance = LazyOptional.of(capability::getDefaultInstance);


    @Override
    public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {

        return cap == capability ? instance.cast() : LazyOptional.empty();
    }

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

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

Storage:

public class PlayerDataStorage implements Capability.IStorage<IPlayerData> {
    @Nullable
    @Override
    public INBT writeNBT(Capability<IPlayerData> capability, IPlayerData instance, Direction side) {
        CompoundNBT tag = new CompoundNBT();
        tag.putFloat("Health", instance.getHealth());
        tag.putInt("Strength", instance.getStrength());
        tag.putInt("Dexterity", instance.getDexterity());
        tag.putInt("Intelligence", instance.getIntelligence());
        return tag;
    }

    @Override
    public void readNBT(Capability<IPlayerData> capability, IPlayerData instance, Direction side, INBT nbt) {
        CompoundNBT tag = (CompoundNBT) nbt;
        instance.setHealth(tag.getFloat("Health"));
        instance.setStrength(tag.getInt("Strength"));
        instance.setDexterity(tag.getInt("Dexterity"));
        instance.setIntelligence(tag.getInt("Intelligence"));
    }
}

@Mod

@Mod.EventBusSubscriber(modid = MajCraft.MOD_ID, bus = Mod.EventBusSubscriber.Bus.FORGE)
public class CapabilityHandler {
    public static final ResourceLocation PLAYER_DATA = new ResourceLocation(MajCraft.MOD_ID, "playerdata");

    @SubscribeEvent
    public void attachCapability(AttachCapabilitiesEvent<Entity> event) {
        if(!(event.getObject() instanceof PlayerEntity)) {
            return; }
        event.addCapability(PLAYER_DATA, new PlayerDataProvider());
    }
}

and finally the place where I am trying to retrieve it (using the LivingJumpEvent just to test it😞

@Mod.EventBusSubscriber(modid = MajCraft.MOD_ID, bus = Mod.EventBusSubscriber.Bus.FORGE, value = Dist.CLIENT)
public class ModClientEvents {

    @SubscribeEvent
    public static void onJump(LivingEvent.LivingJumpEvent event) {

        LivingEntity player = event.getEntityLiving();
        IPlayerData data = player.getCapability(PlayerDataProvider.capability).orElseThrow(IllegalStateException::new);
        data.setHealth(1.0F);
        MajCraft.LOGGER.info("amount of health " + data.getHealth());
    }
}

The game starts fine but the moment I load a world, it crashes with the following error:

[19:27:59] [Server thread/ERROR] [ne.mi.ev.EventBus/EVENTBUS]: Exception caught during firing event: null
	Index: 1
	Listeners:
		0: NORMAL
		1: ASM: class com.majesity.majcraft.events.ModClientEvents onJump(Lnet/minecraftforge/event/entity/living/LivingEvent$LivingJumpEvent;)V
java.lang.IllegalStateException
	at net.minecraftforge.common.util.LazyOptional.orElseThrow(LazyOptional.java:261)
	at com.majesity.majcraft.events.ModClientEvents.onJump(ModClientEvents.java:26)
	at net.minecraftforge.eventbus.ASMEventHandler_2_ModClientEvents_onJump_LivingJumpEvent.invoke(.dynamic)
	at net.minecraftforge.eventbus.ASMEventHandler.invoke(ASMEventHandler.java:80)
	at net.minecraftforge.eventbus.EventBus.post(EventBus.java:258)
	at net.minecraftforge.common.ForgeHooks.onLivingJump(ForgeHooks.java:412)
	at net.minecraft.entity.LivingEntity.jump(LivingEntity.java:2010)
	at net.minecraft.entity.LivingEntity.livingTick(LivingEntity.java:2575)
	at net.minecraft.entity.MobEntity.livingTick(MobEntity.java:536)
	at net.minecraft.entity.monster.MonsterEntity.livingTick(MonsterEntity.java:42)
	at net.minecraft.entity.monster.ZombieEntity.livingTick(ZombieEntity.java:245)
	at net.minecraft.entity.LivingEntity.tick(LivingEntity.java:2300)
	at net.minecraft.entity.MobEntity.tick(MobEntity.java:336)
	at net.minecraft.entity.monster.ZombieEntity.tick(ZombieEntity.java:216)
	at net.minecraft.world.server.ServerWorld.updateEntity(ServerWorld.java:616)
	at net.minecraft.world.World.guardEntityTick(World.java:637)
	at net.minecraft.world.server.ServerWorld.tick(ServerWorld.java:400)
	at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:889)
	at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:825)
	at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:87)
	at net.minecraft.server.MinecraftServer.func_240802_v_(MinecraftServer.java:665)
	at net.minecraft.server.MinecraftServer.lambda$func_240784_a_$0(MinecraftServer.java:231)
	at java.lang.Thread.run(Thread.java:748)

[19:27:59] [Server thread/ERROR] [minecraft/MinecraftServer]: Encountered an unexpected exception
net.minecraft.crash.ReportedException: Ticking entity
	at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:893) ~[?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:825) ~[?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:87) ~[?:?] {re:classloading,pl:runtimedistcleaner:A}
	at net.minecraft.server.MinecraftServer.func_240802_v_(MinecraftServer.java:665) ~[?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.server.MinecraftServer.lambda$func_240784_a_$0(MinecraftServer.java:231) ~[?:?] {re:classloading,pl:accesstransformer:B}
	at java.lang.Thread.run(Thread.java:748) [?:1.8.0_251] {}
Caused by: java.lang.IllegalStateException
	at net.minecraftforge.common.util.LazyOptional.orElseThrow(LazyOptional.java:261) ~[forge-1.16.1-32.0.63_mapped_snapshot_20200707-1.16.1-recomp.jar:?] {re:classloading}
	at com.majesity.majcraft.events.ModClientEvents.onJump(ModClientEvents.java:26) ~[main/:?] {re:classloading}
	at net.minecraftforge.eventbus.ASMEventHandler_2_ModClientEvents_onJump_LivingJumpEvent.invoke(.dynamic) ~[?:?] {}
	at net.minecraftforge.eventbus.ASMEventHandler.invoke(ASMEventHandler.java:80) ~[eventbus-2.2.0-service.jar:?] {}
	at net.minecraftforge.eventbus.EventBus.post(EventBus.java:258) ~[eventbus-2.2.0-service.jar:?] {}
	at net.minecraftforge.common.ForgeHooks.onLivingJump(ForgeHooks.java:412) ~[?:?] {re:classloading}
	at net.minecraft.entity.LivingEntity.jump(LivingEntity.java:2010) ~[?:?] {re:classloading}
	at net.minecraft.entity.LivingEntity.livingTick(LivingEntity.java:2575) ~[?:?] {re:classloading}
	at net.minecraft.entity.MobEntity.livingTick(MobEntity.java:536) ~[?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.entity.monster.MonsterEntity.livingTick(MonsterEntity.java:42) ~[?:?] {re:classloading}
	at net.minecraft.entity.monster.ZombieEntity.livingTick(ZombieEntity.java:245) ~[?:?] {re:classloading}
	at net.minecraft.entity.LivingEntity.tick(LivingEntity.java:2300) ~[?:?] {re:classloading}
	at net.minecraft.entity.MobEntity.tick(MobEntity.java:336) ~[?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.entity.monster.ZombieEntity.tick(ZombieEntity.java:216) ~[?:?] {re:classloading}
	at net.minecraft.world.server.ServerWorld.updateEntity(ServerWorld.java:616) ~[?:?] {re:classloading}
	at net.minecraft.world.World.guardEntityTick(World.java:637) ~[?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.world.server.ServerWorld.tick(ServerWorld.java:400) ~[?:?] {re:classloading}
	at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:889) ~[?:?] {re:classloading,pl:accesstransformer:B}
	... 5 more
AL lib: (EE) alc_cleanup: 1 device not closed

Process finished with exit code -1

onJump line 26 is: 

        IPlayerData data = player.getCapability(PlayerDataProvider.capability).orElseThrow(IllegalStateException::new);

So, the error is in getting the actual capability. I don't know why it has a null value. I have put a lot of effort into this and to no avail... please somebody tell me what I am doing wrong! Thank you for your time

Edited by majesity
Posted (edited)

So 

LivingEvent.LivingJumpEvent

triggers when a LivingEntity jumps, that includes Zombies, Rabbits... entities like that. The problem is they don't have the capability since you only attach the capability to the players. Either attach to all living entities or check if the entity is player in LivingJumpEvent.

Edited by poopoodice
Posted

Oh wow I can't believe I forgot to check that *facepalms*. I fixed that and the world launches fine, but the moment I jump it crashes. Here is the error:

[19:51:49] [Render thread/ERROR] [ne.mi.ev.EventBus/EVENTBUS]: Exception caught during firing event: null
	Index: 1
	Listeners:
		0: NORMAL
		1: ASM: class com.majesity.majcraft.events.ModClientEvents onJump(Lnet/minecraftforge/event/entity/living/LivingEvent$LivingJumpEvent;)V
java.lang.NullPointerException
	at com.majesity.majcraft.events.ModClientEvents.onJump(ModClientEvents.java:30)
	at net.minecraftforge.eventbus.ASMEventHandler_2_ModClientEvents_onJump_LivingJumpEvent.invoke(.dynamic)
	at net.minecraftforge.eventbus.ASMEventHandler.invoke(ASMEventHandler.java:80)
	at net.minecraftforge.eventbus.EventBus.post(EventBus.java:258)
	at net.minecraftforge.common.ForgeHooks.onLivingJump(ForgeHooks.java:412)
	at net.minecraft.entity.LivingEntity.jump(LivingEntity.java:2010)
	at net.minecraft.entity.player.PlayerEntity.jump(PlayerEntity.java:1410)
	at net.minecraft.entity.LivingEntity.livingTick(LivingEntity.java:2575)
	at net.minecraft.entity.player.PlayerEntity.livingTick(PlayerEntity.java:510)
	at net.minecraft.client.entity.player.ClientPlayerEntity.livingTick(ClientPlayerEntity.java:834)
	at net.minecraft.entity.LivingEntity.tick(LivingEntity.java:2300)
	at net.minecraft.entity.player.PlayerEntity.tick(PlayerEntity.java:226)
	at net.minecraft.client.entity.player.ClientPlayerEntity.tick(ClientPlayerEntity.java:198)
	at net.minecraft.client.world.ClientWorld.updateEntity(ClientWorld.java:197)
	at net.minecraft.world.World.guardEntityTick(World.java:637)
	at net.minecraft.client.world.ClientWorld.tickEntities(ClientWorld.java:166)
	at net.minecraft.client.Minecraft.runTick(Minecraft.java:1508)
	at net.minecraft.client.Minecraft.runGameLoop(Minecraft.java:958)
	at net.minecraft.client.Minecraft.run(Minecraft.java:586)
	at net.minecraft.client.main.Main.main(Main.java:184)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at net.minecraftforge.userdev.FMLUserdevClientLaunchProvider.lambda$launchService$0(FMLUserdevClientLaunchProvider.java:55)
	at cpw.mods.modlauncher.LaunchServiceHandlerDecorator.launch(LaunchServiceHandlerDecorator.java:37)
	at cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:54)
	at cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:72)
	at cpw.mods.modlauncher.Launcher.run(Launcher.java:81)
	at cpw.mods.modlauncher.Launcher.main(Launcher.java:65)
	at net.minecraftforge.userdev.LaunchTesting.main(LaunchTesting.java:105)

The onJump line 30 is:

data.setHealth(1.0F);

which is just after I successfully create the data object right here (this is line 29):

IPlayerData data = player.getCapability(PlayerDataProvider.capability).orElse(null);

 

What went wrong this time?

Posted (edited)
        LivingEntity player = event.getEntityLiving();
        IPlayerData data = player.getCapability(PlayerDataProvider.capability).orElseThrow(IllegalStateException::new);

You only attach data to the player. LivingEntity is not necessarily a PlayerEntity.

Edited by Draco18s

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted (edited)
  On 7/24/2020 at 1:02 AM, Draco18s said:
You only attach data to the player. LivingEntity is not necessarily a PlayerEntity.
Expand  

I casted it to a PlayerEntity after checking and I still got the same error.

Edited by majesity
Posted

Show updated code for that event method.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted
    @SubscribeEvent // LivingEntity#func_233480_cy_() --> LivingEntity#getPosition()
    public static void onJump(LivingEvent.LivingJumpEvent event) {

        if(event.getEntityLiving() instanceof PlayerEntity) {

            PlayerEntity player = (PlayerEntity)event.getEntityLiving();
            IPlayerData data = player.getCapability(PlayerDataProvider.capability).orElse(null);
            data.setHealth(1.0F);
            MajCraft.LOGGER.info("amount of health " + data.getHealth());
}
}

All I did was cast it.

Posted (edited)
  On 7/24/2020 at 1:21 AM, Draco18s said:

Show updated code for that event method.

Expand  

I'm pretty sure he fixed that problem. The problem now is he's getting the cap using player.getCapability(...).orElse(null);

And tries to assign value to null.

 

That's also why I asked him if he registered his capability.

Edited by poopoodice
Posted

This is why orElseThrow is a better idea for the event.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted (edited)

My capability is registered properly. I'm still getting the same error:

  Quote

[22:33:04] [Render thread/ERROR] [ne.mi.ev.EventBus/EVENTBUS]: Exception caught during firing event: null
    Index: 1
    Listeners:
        0: NORMAL
        1: ASM: class com.majesity.majcraft.events.ModClientEvents onJump(Lnet/minecraftforge/event/entity/living/LivingEvent$LivingJumpEvent;)V
java.lang.NullPointerException
    at com.majesity.majcraft.events.ModClientEvents.onJump(ModClientEvents.java:30)
    at net.minecraftforge.eventbus.ASMEventHandler_3_ModClientEvents_onJump_LivingJumpEvent.invoke(.dynamic)
    at net.minecraftforge.eventbus.ASMEventHandler.invoke(ASMEventHandler.java:80)
    at net.minecraftforge.eventbus.EventBus.post(EventBus.java:258)
    at net.minecraftforge.common.ForgeHooks.onLivingJump(ForgeHooks.java:412)
    at net.minecraft.entity.LivingEntity.jump(LivingEntity.java:2010)
    at net.minecraft.entity.player.PlayerEntity.jump(PlayerEntity.java:1410)
    at net.minecraft.entity.LivingEntity.livingTick(LivingEntity.java:2575)
    at net.minecraft.entity.player.PlayerEntity.livingTick(PlayerEntity.java:510)
    at net.minecraft.client.entity.player.ClientPlayerEntity.livingTick(ClientPlayerEntity.java:834)
    at net.minecraft.entity.LivingEntity.tick(LivingEntity.java:2300)
    at net.minecraft.entity.player.PlayerEntity.tick(PlayerEntity.java:226)
    at net.minecraft.client.entity.player.ClientPlayerEntity.tick(ClientPlayerEntity.java:198)
    at net.minecraft.client.world.ClientWorld.updateEntity(ClientWorld.java:197)
    at net.minecraft.world.World.guardEntityTick(World.java:637)
    at net.minecraft.client.world.ClientWorld.tickEntities(ClientWorld.java:166)
    at net.minecraft.client.Minecraft.runTick(Minecraft.java:1508)
    at net.minecraft.client.Minecraft.runGameLoop(Minecraft.java:958)
    at net.minecraft.client.Minecraft.run(Minecraft.java:586)
    at net.minecraft.client.main.Main.main(Main.java:184)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.minecraftforge.userdev.FMLUserdevClientLaunchProvider.lambda$launchService$0(FMLUserdevClientLaunchProvider.java:55)
    at cpw.mods.modlauncher.LaunchServiceHandlerDecorator.launch(LaunchServiceHandlerDecorator.java:37)
    at cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:54)
    at cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:72)
    at cpw.mods.modlauncher.Launcher.run(Launcher.java:81)
    at cpw.mods.modlauncher.Launcher.main(Launcher.java:65)
    at net.minecraftforge.userdev.LaunchTesting.main(LaunchTesting.java:105)
 

Expand  

Here is how I registered my capability in my main mod class (called MajCraft):

private void setup(final FMLCommonSetupEvent event)
    {
        CapabilityManager.INSTANCE.register(IPlayerData.class, new PlayerDataStorage(), PlayerDataFactory::new);
}

 

Edited by majesity
i was being dumb
Posted
  On 7/24/2020 at 3:15 AM, majesity said:

Cannot register a capability implementation multiple times : com.majesity.majcraft.capabilities.IPlayerData

Expand  

You also have it in PlayerData:

 

  On 7/23/2020 at 7:53 PM, majesity said:

public static void register() {

    CapabilityManager.INSTANCE.register(IPlayerData.class, new PlayerData.Storage(), PlayerData::new);

}

Expand  

Assuming the class still exists (it is unclear, as we don't have your full source code, eg. a github repository). Use your IDE to search for references to the register() method and find where you're calling it in your code and I bet you'll find the offender.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted
  On 7/24/2020 at 10:45 AM, diesieben07 said:

You never attach your capability to anything, because your AttachCapabilitiesEvent handler is not registered. @EventBusSubscriber registers the class to the event bus, meaning only static methods will be registered.

Expand  

Yes! This worked! Thank you so much. I can't express how grateful I am, I've spent nearly three days trying to figure out this issue and it finally works. Thank you.

  • Haha 1

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

    • After some time minecraft crashes with an error. Here is the log https://drive.google.com/file/d/1o-2R6KZaC8sxjtLaw5qj0A-GkG_SuoB5/view?usp=sharing
    • The specific issue is that items in my inventory wont stack properly. For instance, if I punch a tree down to collect wood, the first block I collected goes to my hand. So when I punch the second block of wood to collect it, it drops, but instead of stacking with the piece of wood already in my hand, it goes to the second slot in my hotbar instead. Another example is that I'll get some dirt, and then when I'm placing it down later I'll accidentally place a block where I don't want it. When I harvest it again, it doesn't go back to the stack that it came from on my hotbar, where it should have gone, but rather into my inventory. That means that if my inventory is full, then the dirt wont be picked up even though there should be space available in the stack I'm holding. The forge version I'm using is 40.3.0, for java 1.18.2. I'll leave the mods I'm using here, and I'd appreciate it if anybody can point me in the right direction in regards to figuring out how to fix this. I forgot to mention that I think it only happens on my server but I&#39;m not entirely sure. PLEASE HELP ME! LIST OF THE MODS. aaa_particles Adorn AdvancementPlaques AI-Improvements AkashicTome alexsdelight alexsmobs AmbientSounds amwplushies Animalistic another_furniture AppleSkin Aquaculture aquamirae architectury artifacts Atlas-Lib AutoLeveling AutoRegLib auudio balm betterfpsdist biggerstacks biomancy BiomesOPlenty blockui blueprint Bookshelf born_in_chaos Botania braincell BrassAmberBattleTowers brutalbosses camera CasinoCraft cfm (MrCrayfish’s Furniture Mod) chat_heads citadel cloth-config Clumps CMDCam CNB cobweb collective comforts convenientcurioscontainer cookingforblockheads coroutil CosmeticArmorReworked CozyHome CrabbersDelight crashexploitfixer crashutilities Create CreativeCore creeperoverhaul cristellib crittersandcompanions Croptopia CroptopiaAdditions CullLessLeaves curios curiouslanterns curiouslights Curses' Naturals CustomNPCs CyclopsCore dannys_expansion decocraft Decoration Mod DecorationDelightRefurbished Decorative Blocks Disenchanting DistantHorizons doubledoors DramaticDoors drippyloadingscreen durabilitytooltip dynamic-fps dynamiclights DynamicTrees DynamicTreesBOP DynamicTreesPlus Easy Dungeons EasyAnvils EasyMagic easy_npc eatinganimation ecologics effective_fg elevatorid embeddium emotecraft enchantlimiter EnchantmentDescriptions EnderMail engineersdecor entityculling entity_model_features entity_texture_features epicfight EvilCraft exlinefurniture expandability explosiveenhancement factory-blocks fairylights fancymenu FancyVideo FarmersDelight fast-ip-ping FastSuite ferritecore finsandtails FixMySpawnR Forge Middle Ages fossil FpsReducer2 furnish GamingDeco geckolib goblintraders goldenfood goodall H.e.b habitat harvest-with-ease hexerei hole_filler huge-structure-blocks HunterIllager iammusicplayer Iceberg illuminations immersive_paintings incubation infinitybuttons inventoryhud InventoryProfilesNext invocore ItemBorders itemzoom Jade jei (Just Enough Items) JetAndEliasArmors journeymap JRFTL justzoom kiwiboi Kobolds konkrete kotlinforforge lazydfu LegendaryTooltips libIPN lightspeed lmft lodestone LongNbtKiller LuckPerms Lucky77 MagmaMonsters malum ManyIdeasCore ManyIdeasDoors marbledsarsenal marg mcw-furniture mcw-lights mcw-paths mcw-stairs mcw-trapdoors mcw-windows meetyourfight melody memoryleakfix Mimic minecraft-comes-alive MineTraps minibosses MmmMmmMmmMmm MOAdecor (ART, BATH, COOKERY, GARDEN, HOLIDAYS, LIGHTS, SCIENCE) MobCatcher modonomicon mods_optimizer morehitboxes mowziesmobs MutantMonsters mysticalworld naturalist NaturesAura neapolitan NekosEnchantedBooks neoncraft2 nerb nifty NightConfigFixes nightlights nocube's_villagers_sell_animals NoSeeNoTick notenoughanimations obscure_api oculus oresabovediamonds otyacraftengine Paraglider Patchouli physics-mod Pillagers Gun PizzaCraft placeableitems Placebo player-animation-lib pneumaticcraft-repressurized polymorph PrettyPipes Prism projectbrazier Psychadelic-Chemistry PuzzlesLib realmrpg_imps_and_demons RecipesLibrary reeves-furniture RegionsUnexplored restrictedportals revive-me Scary_Mobs_And_Bosses selene shetiphiancore ShoulderSurfing smoothboot
    • Hi everyone, I'm currently developing a Forge 1.21 mod for Minecraft and I want to display a custom HUD overlay for a minigame. My goal: When the game starts, all players should see an item/block icon (from the base game, not a custom texture) plus its name/text in the HUD – similar to how the bossbar overlay works. The HUD should appear centered above the hotbar (or at a similar prominent spot), and update dynamically (icon and name change as the target item changes). What I've tried: I looked at many online tutorials and several GitHub repos (e.g. SeasonHUD, MiniHUD), but most of them use NeoForge or Forge versions <1.20 that provide the IGuiOverlay API (e.g. implements IGuiOverlay, RegisterGuiOverlaysEvent). In Forge 1.21, it seems that neither IGuiOverlay nor RegisterGuiOverlaysEvent exist anymore – at least, I can't import them and they are missing from the docs and code completion. I tried using RenderLevelStageEvent as a workaround but it is probably not intended for custom HUDs. I am not using NeoForge, and switching the project to NeoForge is currently not an option for me. I tried to look at the original minecraft source code to see how elements like hearts, hotbar etc are drawn on the screen but I am too new to Minecraft modding to understand. What I'm looking for: What is the correct way to add a custom HUD element (icon + text) in Forge 1.21, given that the previous overlay API is missing? Is there a new recommended event, callback, or method in Forge 1.21 for custom HUD overlays, or is everyone just using a workaround? Is there a minimal open-source example repo for Forge 1.21 that demonstrates a working HUD overlay without relying on NeoForge or deprecated Forge APIs? My ideal solution: Centered HUD element with an in-game item/block icon (from the base game's assets, e.g. a diamond or any ItemStack / Item) and its name as text, with a transparent background rectangle. It should be visible to the players when the mini game is running. Easy to update the item (e.g. static variable or other method), so it can change dynamically during the game. Any help, code snippets, or up-to-date references would be really appreciated! If this is simply not possible right now in Forge 1.21, it would also help to know that for sure. Thank you very much in advance!
    • The simple answer is there is not an easy way. You would need to know how to program in Java, as well as at least some familiarity with how Forge works so you could port the differences. You would also need the sourcecode for the original mod, and permission from the author to modify it, if they did not use some sort of open source license. So it's not impossible, but it would take some effort, but doing so would open up a whole new world of possibilities for you!
  • Topics

×
×
  • Create New...

Important Information

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