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
9 minutes ago, majesity said:

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

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

18 minutes ago, majesity said:

Capability<Optional<PlayerData>> getCapability();

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

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)
9 minutes ago, Draco18s said:

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

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)
10 minutes ago, Draco18s said:

Show updated code for that event method.

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)
 

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
18 minutes ago, majesity said:

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

You also have it in PlayerData:

 

7 hours ago, majesity said:

public static void register() {

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

}

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
17 hours ago, 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.

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



×
×
  • Create New...

Important Information

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