Jump to content

[SOLVED] [1.14.4] How do you use capabilities to store variables such as thirst in the player entity?


thebadscientist

Recommended Posts

5 hours ago, diesieben07 said:

What about the documentation is lacking? What have you tried?

that's for 1.13, which is outdated.

for instance, 1.14 does not have the hasCapability method from ICapabilityProvider and makes no mention of LazyOptional.

 

what I did is tried looking at source code from 1.12 and 1.13 mods and see if I could adapt the code to 1.14 but it didn't end too well.

Link to comment
Share on other sites

Post your code.

1.14 hasn’t changed much from 1.13.

Some tips:

Spoiler

Modder Support:

Spoiler

1. Do not follow tutorials on YouTube, especially TechnoVision (previously called Loremaster) and HarryTalks, due to their promotion of bad practice and usage of outdated code.

2. Always post your code.

3. Never copy and paste code. You won't learn anything from doing that.

4. 

Quote

Programming via Eclipse's hotfixes will get you nowhere

5. Learn to use your IDE, especially the debugger.

6.

Quote

The "picture that's worth 1000 words" only works if there's an obvious problem or a freehand red circle around it.

Support & Bug Reports:

Spoiler

1. Read the EAQ before asking for help. Remember to provide the appropriate log(s).

2. Versions below 1.11 are no longer supported due to their age. Update to a modern version of Minecraft to receive support.

 

 

Link to comment
Share on other sites

On 1/3/2020 at 6:26 AM, DavidM said:

Post your code.

1.14 hasn’t changed much from 1.13.

It's an attempt to adapt from 1.12 not 1.13

 

CustomClass:

Spoiler

public class CustomClass implements ICustomClass{

    private int counter;
    private byte version;

    public CustomClass(){
        this.counter = 20;
        this.version = (byte) 1;
    }

    @Override
    public void setVersion(byte version) {
        this.version = version;
    }

    @Override
    public byte getVersion() {
        return version;
    }

    @Override
    public void setCounter(int value) {
        this.counter = value;
    }

    @Override
    public int getCounter() {
        return counter;
    }

    @Override
    public void copyForRespawn(ICustomClass deadPlayer) {
        this.setCounter(deadPlayer.getCounter());
    }

    public static ICustomClass getFromPlayer(PlayerEntity player){
        return player.getCapability(PlayerDispatcher.PLAYER_COUNTER, null).orElseThrow(() -> new IllegalArgumentException(("LazyOptional must not be empty!")));
    }
}

 

PlayerDispatcher:

Spoiler

public class PlayerDispatcher implements ICapabilitySerializable<CompoundNBT> {

    @CapabilityInject(ICustomClass.class)
    public static final Capability<ICustomClass> PLAYER_COUNTER = null;

    private LazyOptional<ICustomClass> instance;

    @Override
    public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
        if (cap != PLAYER_COUNTER)
            return LazyOptional.empty();
        if (this.instance == null){
            this.instance = LazyOptional.of(PLAYER_COUNTER::getDefaultInstance);
        }
        return this.instance.cast();
    }

    @Override
    public CompoundNBT serializeNBT() {
        return (CompoundNBT) PLAYER_COUNTER.getStorage().writeNBT(PLAYER_COUNTER, this.getCapability(PLAYER_COUNTER, null).orElse(null), null);
    }

    @Override
    public void deserializeNBT(CompoundNBT nbt) {
        PLAYER_COUNTER.getStorage().readNBT(PLAYER_COUNTER, this.getCapability(PLAYER_COUNTER, null).orElse(null), null, nbt);
    }
}

 

CounterStorage:

Spoiler

public class CounterStorage implements Capability.IStorage<ICustomClass> {

    @Override
    public INBT writeNBT(Capability<ICustomClass> capability, ICustomClass instance, Direction side) {
        CompoundNBT tag = new CompoundNBT();
        tag.putInt("counter", instance.getCounter());
        tag.putByte("version", instance.getVersion());
        return tag;
    }

    @Override
    public void readNBT(Capability<ICustomClass> capability, ICustomClass instance, Direction side, INBT nbt) {
        CompoundNBT tag = (CompoundNBT) nbt;
        instance.setCounter(tag.getInt("counter"));
        instance.setVersion(tag.getByte("version"));
    }
}

 

PlayerPropertiesEvent:

Spoiler

public class PlayerPropertiesEvent {

    @SubscribeEvent
    public void onPlayerLogIn(net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent event){

        PlayerEntity player = event.getPlayer();
        World world = player.world;

        if (!world.isRemote){
            ICustomClass instance = CustomClass.getFromPlayer(player);
            Capability<ICustomClass> cap = PlayerDispatcher.PLAYER_COUNTER;
            cap.getStorage().readNBT(cap, instance, null, player.getEntityData().getCompound(cap.getName()));
        }
	}
                  @SubscribeEvent
    public void onEntityConstruction(AttachCapabilitiesEvent<Entity> event) {
        if (event.getObject() instanceof PlayerEntity){
            event.addCapability(new ResourceLocation(PracticeMod.MODID, "counter"), new PlayerDispatcher());
        }
    }

    @SubscribeEvent
    public void onPlayerCloned(PlayerEvent.Clone event){
        PlayerEntity deadPlayer = event.getOriginal();
        PlayerEntity newPlayer = event.getEntityPlayer();
        ICustomClass oldCounter = CustomClass.getFromPlayer(deadPlayer);
        ICustomClass newCounter = CustomClass.getFromPlayer(newPlayer);
        newCounter.copyForRespawn(oldCounter);
    }

    @SubscribeEvent
    public static void onPlayerTick(TickEvent.PlayerTickEvent event){
        PlayerEntity player = event.player;
        World world = player.world;

        if(!world.isRemote){
            if(event.phase == TickEvent.Phase.START){
                ICustomClass instance = CustomClass.getFromPlayer(player);
                Capability<ICustomClass> cap = PlayerDispatcher.PLAYER_COUNTER;
                player.getEntityData().put(cap.getName(), cap.getStorage().writeNBT(cap, instance, null));
            }
        }
    }
}

 

EventHandler: (this increases the value I want to store)

Spoiler

@Mod.EventBusSubscriber
public class EventHandler {

    @SubscribeEvent
    public static void onTest(PlayerInteractEvent.RightClickItem event) {

        PlayerEntity player = event.getEntityPlayer();
        ICustomClass cap = CustomClass.getFromPlayer(player);

        if (event.getItemStack().getItem() == Items.GUNPOWDER) {
            cap.setCounter(cap.getCounter() + 10);
            PracticeMod.LOGGER.info("new value is: " + cap.getCounter());
        }
    }

    @SubscribeEvent
    public static void onAirRightClick(PlayerInteractEvent.RightClickEmpty event) {

        PlayerEntity player = event.getEntityPlayer();
        ICustomClass cap = CustomClass.getFromPlayer(player);
        ItemStack item = player.getHeldItemMainhand();

        if (item.isEmpty()) {
            PracticeMod.LOGGER.info("Current value is: " + cap.getCounter());
        }
    }
}

 

 

Link to comment
Share on other sites

6 hours ago, diesieben07 said:

This double lazy initialization is not necessary. The point of LazyOptional is that its lazy already (hence the name). No need to create the LazyOptional lazily.

I copied from some mod, oh well. So what should the getCapability look like then? I still don't quite understand LazyOptional tbh

6 hours ago, diesieben07 said:

Are you for real...?

My mistake, copied some old code, what I actually put was this, is this ok or is it bad as well?

this.getCapability(PLAYER_COUNTER, null).orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!"))

 

6 hours ago, diesieben07 said:

This makes zero sense. getEntityData has nothing to do with capabilities, this does nothing useful.

Ye probably shouldn't adapt code from two different mods (it's from ToughAsNails, which I thought could be useful)

Edited by thebadscientist
Link to comment
Share on other sites

On 1/5/2020 at 8:54 PM, diesieben07 said:

It should just return a field from your class, which holds the LazyOptional. Create the LazyOptional in your constructor and put it in a final field.

The point of LazyOptional is to provide an optional value (it can be present or not) in a lazy way (i.e. only create the value once it's needed). That's why you give a Supplier to the LazyOptional instead of the actual value.

 

You can do that, but you could just as well just access the capability instance directly, stored in a field.

 

Don't take this mod's code for anything. I haven't seen anything good in it.

Alright, I think I got everything sorted except that the value I want to store gets reset to 0 everytime I log into the world:

[23:41:41.634] [Server thread/INFO] [co.de.pr.se.PracticeMod/]: reading NBT!
[23:41:41.634] [Server thread/INFO] [co.de.pr.se.PracticeMod/]: NBT Data: 120
[23:41:41.634] [Server thread/INFO] [co.de.pr.se.PracticeMod/]: Instance Data: 120
[23:41:41.636] [Server thread/INFO] [minecraft/PlayerList]: Dev[local:E:2d267046] logged in with entity id 372 at (193.58322637936269, 72.0, -162.9556295622775)
[23:41:41.642] [Server thread/INFO] [minecraft/MinecraftServer]: Dev joined the game
[23:41:41.719] [Server thread/INFO] [co.de.pr.se.PracticeMod/]: PLAYER LOGIN EVENT
[23:41:41.719] [Server thread/INFO] [co.de.pr.se.PracticeMod/]: reading NBT!
[23:41:41.719] [Server thread/INFO] [co.de.pr.se.PracticeMod/]: NBT Data: 0
[23:41:41.719] [Server thread/INFO] [co.de.pr.se.PracticeMod/]: Instance Data: 0

Do you know what would cause this?

Link to comment
Share on other sites

  • thebadscientist changed the title to [SOLVED] [1.14.4] How do you use capabilities to store variables such as thirst in the player entity?
2 hours ago, thebadscientist said:

nvm got it working.

How did you get it working, for other people with the same problem in the future?

About Me

Spoiler

My Discord - Cadiboo#8887

My WebsiteCadiboo.github.io

My ModsCadiboo.github.io/projects

My TutorialsCadiboo.github.io/tutorials

Versions below 1.14.4 are no longer supported on this forum. Use the latest version to receive support.

When asking support remember to include all relevant log files (logs are found in .minecraft/logs/), code if applicable and screenshots if possible.

Only download mods from trusted sites like CurseForge (minecraft.curseforge.com). A list of bad sites can be found here, with more information available at stopmodreposts.org

Edit your own signature at www.minecraftforge.net/forum/settings/signature/ (Make sure to check its compatibility with the Dark Theme)

Link to comment
Share on other sites

On 1/7/2020 at 2:31 AM, Cadiboo said:

How did you get it working, for other people with the same problem in the future?

You mean regarding the value resetting to 0 or regarding the whole capability implementation?

 

Either way, check my GitHub repository to see how I implemented it. 

https://github.com/deneth-weerasinghe/PracticeMod

Note the capability's stored value is increased by 10 when right-clicking water with a custom item I made.

  • Thanks 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Dalam dunia perjudian online yang berkembang pesat, mencari platform yang dapat memberikan kemenangan maksimal dan hasil terbaik adalah impian setiap penjudi. OLXTOTO, dengan bangga, mempersembahkan dirinya sebagai jawaban atas pencarian itu. Sebagai platform terbesar untuk kemenangan maksimal dan hasil optimal, OLXTOTO telah menciptakan gelombang besar di komunitas perjudian online. Satu dari banyak keunggulan yang dimiliki OLXTOTO adalah koleksi permainan yang luas dan beragam. Dari togel hingga slot online, dari live casino hingga permainan kartu klasik, OLXTOTO memiliki sesuatu untuk setiap pemain. Dibangun dengan teknologi terkini dan dikembangkan oleh para ahli industri, setiap permainan di platform ini dirancang untuk memberikan pengalaman yang tak tertandingi bagi para penjudi. Namun, keunggulan OLXTOTO tidak hanya terletak pada variasi permainan yang mereka tawarkan. Mereka juga menonjol karena komitmen mereka terhadap keamanan dan keadilan. Dengan sistem keamanan tingkat tinggi dan proses audit yang ketat, OLXTOTO memastikan bahwa setiap putaran permainan berjalan dengan adil dan transparan. Para pemain dapat merasa aman dan yakin bahwa pengalaman berjudi mereka di OLXTOTO tidak akan terganggu oleh masalah keamanan atau keadilan. Tak hanya itu, OLXTOTO juga terkenal karena layanan pelanggan yang luar biasa. Tim dukungan mereka selalu siap sedia untuk membantu para pemain dengan segala pertanyaan atau masalah yang mereka hadapi. Dengan respon cepat dan solusi yang efisien, OLXTOTO memastikan bahwa pengalaman berjudi para pemain tetap mulus dan menyenangkan. Dengan semua fitur dan keunggulan yang ditawarkannya, tidak mengherankan bahwa OLXTOTO telah menjadi pilihan utama bagi jutaan penjudi online di seluruh dunia. Jika Anda mencari platform yang dapat memberikan kemenangan maksimal dan hasil optimal, tidak perlu mencari lebih jauh dari OLXTOTO. Bergabunglah dengan OLXTOTO hari ini dan mulailah petualangan Anda menuju kemenangan besar dan hasil terbaik!
    • Selamat datang di OLXTOTO, situs slot gacor terpanas yang sedang booming di industri perjudian online. Jika Anda mencari pengalaman bermain yang luar biasa, maka OLXTOTO adalah tempat yang tepat untuk Anda. Dapatkan sensasi tidak biasa dengan variasi slot online terlengkap dan peluang memenangkan jackpot slot maxwin yang sering. Di sini, Anda akan merasakan keseruan yang luar biasa dalam bermain judi slot. DAFTAR OLXTOTO DISINI LOGIN OLXTOTO DISINI AKUN PRO OLXTOTO DISINI   Jackpot Slot Maxwin Sering Untuk Peluang Besar Di OLXTOTO, kami tidak hanya memberikan hadiah slot biasa, tapi juga memberikan kesempatan kepada pemain untuk memenangkan jackpot slot maxwin yang sering. Dengan demikian, Anda dapat meraih keberuntungan besar dan memenangkan ribuan rupiah sebagai hadiah jackpot slot maxwin kami. Jackpot slot maxwin merupakan peluang besar bagi para pemain judi slot untuk meraih keuntungan yang lebih besar. Dalam permainan kami, Anda tidak harus terpaku pada kemenangan biasa saja. Kami hadir dengan jackpot slot maxwin yang sering, sehingga Anda memiliki peluang yang lebih besar untuk meraih kemenangan besar dengan hadiah yang menggiurkan. Dalam permainan judi slot, pengalaman bermain bukan hanya tentang keseruan dan hiburan semata. Kami memahami bahwa para pemain juga menginginkan kesempatan untuk meraih keberuntungan besar. Oleh karena itu, OLXTOTO hadir dengan jackpot slot maxwin yang sering untuk memberikan peluang besar kepada para pemain kami. Peluang Besar Menang Jackpot Slot Maxwin Peluang menang jackpot slot maxwin di OLXTOTO sangatlah besar. Anda tidak perlu khawatir tentang batasan atau pembatasan dalam meraih jackpot tersebut. Kami ingin memberikan kesempatan kepada semua pemain kami untuk merasakan sensasi menang dalam jumlah yang luar biasa. Jackpot slot maxwin kami dibuka untuk semua pemain judi slot di OLXTOTO. Anda memiliki peluang yang sama dengan pemain lainnya untuk memenangkan hadiah jackpot yang besar. Kami percaya bahwa semua orang memiliki kesempatan untuk meraih keberuntungan besar, dan itulah mengapa kami menyediakan jackpot slot maxwin yang sering untuk memenuhi harapan dan keinginan Anda.   Kesimpulan OLXTOTO adalah situs slot gacor terbaik yang memberikan pengalaman bermain judi slot online yang tak terlupakan. Dengan variasi slot online terlengkap dan peluang memenangkan jackpot slot maxwin yang sering, OLXTOTO menjadi pilihan terbaik bagi para pemain yang mencari kesenangan dan kemenangan besar dalam perjudian online. Di samping itu, OLXTOTO juga menawarkan layanan pelanggan yang ramah dan responsif, siap membantu setiap pemain dalam mengatasi masalah teknis atau pertanyaan seputar perjudian online. Kami menjaga integritas game dan memberikan lingkungan bermain yang adil serta menjalankan kebijakan perlindungan pelanggan yang cermat. Bergabunglah dengan OLXTOTO sekarang dan nikmati pengalaman bermain slot online yang luar biasa. Jadilah bagian dari komunitas perjudian yang mengagumkan ini dan raih kesempatan untuk meraih kemenangan besar. Dapatkan akses mudah dan praktis ke situs OLXTOTO dan rasakan sensasi bermain judi slot yang tak terlupakan.  
    • OLXTOTO: Platform Maxwin dan Gacor Terbesar Sepanjang Masa Di dunia perjudian online yang begitu kompetitif, mencari platform yang dapat memberikan kemenangan maksimal (Maxwin) dan hasil terbaik (Gacor) adalah prioritas bagi para penjudi yang cerdas. Dalam upaya ini, OLXTOTO telah muncul sebagai pemain kunci yang mengubah lanskap perjudian online dengan menawarkan pengalaman tanpa tandingan.     Sejak diluncurkan, OLXTOTO telah menjadi sorotan industri perjudian online. Dikenal sebagai "Platform Maxwin dan Gacor Terbesar Sepanjang Masa", OLXTOTO telah menarik perhatian pemain dari seluruh dunia dengan reputasinya yang solid dan kinerja yang luar biasa. Salah satu fitur utama yang membedakan OLXTOTO dari pesaingnya adalah komitmen mereka untuk memberikan pengalaman berjudi yang unik dan memuaskan. Dengan koleksi game yang luas dan beragam, termasuk togel, slot online, live casino, dan banyak lagi, OLXTOTO menawarkan sesuatu untuk semua orang. Dibangun dengan teknologi terkini dan didukung oleh tim ahli yang berdedikasi, platform ini memastikan bahwa setiap pengalaman berjudi di OLXTOTO tidak hanya menghibur, tetapi juga menguntungkan. Namun, keunggulan OLXTOTO tidak hanya terletak pada permainan yang mereka tawarkan. Mereka juga terkenal karena keamanan dan keadilan yang mereka berikan kepada para pemain mereka. Dengan sistem keamanan tingkat tinggi dan audit rutin yang dilakukan oleh otoritas regulasi independen, para pemain dapat yakin bahwa setiap putaran permainan di OLXTOTO adalah adil dan transparan. Tidak hanya itu, OLXTOTO juga dikenal karena layanan pelanggan yang luar biasa. Dengan tim dukungan yang ramah dan responsif, para pemain dapat yakin bahwa setiap pertanyaan atau masalah mereka akan ditangani dengan cepat dan efisien. Dengan semua fitur dan keunggulan yang ditawarkannya, tidak mengherankan bahwa OLXTOTO telah menjadi platform pilihan bagi para penjudi online yang mencari kemenangan maksimal dan hasil terbaik. Jadi, jika Anda ingin bergabung dengan jutaan pemain yang telah merasakan keajaiban OLXTOTO, jangan ragu untuk mendaftar dan mulai bermain hari ini!  
    • OLXTOTO adalah bandar slot yang terkenal dan terpercaya di Indonesia. Mereka menawarkan berbagai jenis permainan slot yang menarik dan menghibur. Dengan tampilan yang menarik dan grafis yang berkualitas tinggi, pemain akan merasa seperti berada di kasino sungguhan. OLXTOTO juga menyediakan layanan pelanggan yang ramah dan responsif, siap membantu pemain dengan segala pertanyaan atau masalah yang mereka hadapi. Daftar =  https://surkale.me/Olxtotodotcom1
    • DAFTAR & LOGIN BIGO4D   Bigo4D adalah situs slot online yang populer dan menarik perhatian banyak pemain slot di Indonesia. Dengan berbagai game slot yang unik dan menarik, Bigo4D menjadi tempat yang ideal untuk pemula dan pahlawan slot yang berpengalaman. Dalam artikel ini, kami akan membahas tentang Bigo4D sebagai situs slot terbesar dan menarik yang saat ini banyak dijajaki oleh pemain slot online.
  • Topics

×
×
  • Create New...

Important Information

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