Jump to content

[1.14.4] How to store simple information to each save?


TeryWells

Recommended Posts

I have some information, just strings and ints, that I need to store to the world save. I looked into WorldSavedData, but I'm not sure whether or not this is what I am supposed to use? I am also very confused about WorldSavedData and how to use it. I'd just like to know what the best way to store this data would be and how I go about do so (beginner here). Thanks!

Edited by TeryWells
typo
Link to comment
Share on other sites

Well I'll only actually set these on world creation and this way the user can go in and customize the values if they so please. But I'll take your word that that is not a good idea haha. I've been playing around with WorldCapabilityData and I'm just thoroughly confused at this point. Like I said I'm very much beginner, I imagine everything I'm doing is incorrect but here's whats going on:

public class ModData extends WorldCapabilityData {

    private final String key = Epicity.modid;
    public CompoundNBT data;

    public ModData(String name) { super(name); }

    public CompoundNBT get() {
        data.putInt("color", (int) Math.floor(Math.random() * 16777215));
        markDirty();
        return data;
    }

    @Override
    public void read(CompoundNBT compound) {
        this.data = compound.getCompound(key);
    }

    @Override
    public CompoundNBT write(CompoundNBT compound) {
        compound.put(key, data);
        return compound;
    }
}

and then 

public static ModData mapData;
...
private void clientRegistries(final FMLClientSetupEvent event) {
    Minecraft.getInstance().getBlockColors().register((state, worldIn, pos, tintIndex) -> mapData.get().getInt("color"), ModBlocks.blockity);
    Minecraft.getInstance().getItemColors().register((stack, tintIndex) -> mapData.get().getInt("color"), ModItems.blockity);
}

I don't even know if its actually saving because I get NullPointerException when I load up a world and look at the block.

Link to comment
Share on other sites

Okay I have switched it over to WorldSavedData and removed using nbt. I tried using the WorldEvent.Load event to get the world, but I'm not sure to go from here.

 

Most people previously seem to do things with MapStorage however that doesn't exist in 1.14 apparently.

 

Thanks

Edited by TeryWells
Link to comment
Share on other sites

Took me a little while to better understand capabilities but I think I'm understanding them better now. I've written up the basics, however it doesn't seem to actually be working when I try to get and set the color integer.

Spoiler

Blockity


public void onBlockPlacedBy(World worldIn, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) {
        if (!worldIn.isRemote()) {
            IModData x = ModDataUtil.getModData(worldIn);
            if (x.getColor() == 0) {
                x.setColor((int) Math.ceil(Math.random() * 16777));
            }

            placer.sendMessage(new StringTextComponent("Color: " + x.getColor()));
        }
    }

ModDataUtil


public final class ModDataUtil {
    public static IModData getModData(ICapabilityProvider world) {
        return world.getCapability(ModDataCapability.INSTANCE)
                .orElseGet(ModDataCapability::new);
    }
}

 

Spoiler

ModDataCapacity


public class ModDataCapability implements IModData, ICapabilitySerializable<CompoundNBT> {
    @CapabilityInject(IModData.class)
    public static Capability<IModData> INSTANCE;
    public static ResourceLocation NAME = new ResourceLocation(Epicity.modid, "mod_data");

    private final LazyOptional<IModData> holder = LazyOptional.of(() -> this);

    private int color;

    @Override
    public int getColor() {
        return this.color;
    }

    @Override
    public void setColor(int color) {
        this.color = color;
    }

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

    @Override
    public CompoundNBT serializeNBT() {
        CompoundNBT nbt = new CompoundNBT();
        nbt.putInt("color", this.color);
        return nbt;
    }

    @Override
    public void deserializeNBT(CompoundNBT nbt) {
        this.color = nbt.getInt("color");
    }

    public static boolean canAttachTo(ICapabilityProvider obj) {
        try {
            if (obj.getCapability(INSTANCE).isPresent()) {
                return false;
            }
        } catch (NullPointerException ex) {
            // Forge seems to be screwing up somewhere?
            Epicity.logger.error("Failed to get capabilities from {}", obj);
            return false;
        }
        return obj instanceof World;
    }

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

    private static class Storage implements Capability.IStorage<IModData> {

        @Nullable
        @Override
        public INBT writeNBT(Capability<IModData> capability, IModData instance, Direction side) {
            if (instance instanceof ModDataCapability) {
                return ((ModDataCapability) instance).serializeNBT();
            }
            return new CompoundNBT();
        }

        @Override
        public void readNBT(Capability<IModData> capability, IModData instance, Direction side, INBT nbt) {
            if (instance instanceof ModDataCapability) {
                ((ModDataCapability) instance).deserializeNBT((CompoundNBT) nbt);
            }
        }
    }
}

I largely used this to write my own capability

if I removed .orElseGet(ModDataCapability::new),

world.getCapability(ModDataCapability.INSTANCE)

gives the error Incompatible types. Required IModData but 'getCapability' was inferred to LazyOptional<T>: Not instances of type variables T exist so LazyOptional<T> conforms to IModData

Link to comment
Share on other sites

Okay so I have a function to set the color to a random number if the color is equal to 0, and then get the color and print it. This is in blockity#onBlockPlacedBy. Now in the game it will print it out, but even after placing the block, which should mean color is no longer equal to 0, it still continues to randomize the value of color even though it is no longer equal to 1. 

    public void onBlockPlacedBy(World worldIn, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) {
        if (!worldIn.isRemote()) {
            IModData x = ModDataUtil.getModData(worldIn);
            if (x.getColor() == 0) {
                x.setColor((int) Math.ceil(Math.random() * 16777));
            }
            placer.sendMessage(new StringTextComponent("Color: " + x.getColor()));
        }
    }

Here is the getModData function:

public static IModData getModData(ICapabilityProvider world) {
        return world.getCapability(ModDataCapability.INSTANCE)
                .orElseGet(ModDataCapability::new);
    }

I think the above is the issue but I don't know what I'm doing wrong here?

Edited by TeryWells
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

    • Slot Bank BNI adalah pilihan tergacor untuk memulai bermain slot judi Online dimuka bumi saat ini. Jika anda mempunyai Bank BNI, Anda berkesempatan mendapatkan Akun Pro atau ID pro untuk bermain slot. Tunggu apa lagi? Segera daftarkan diri anda sekarang dan dapatkan kemewahan menang maxwin di Museumbola.
    • Halo para penggemar slot online! Apakah Anda mencari pengalaman bermain slot yang seru dan menguntungkan? Apakah Anda ingin menikmati slot gacor dari server Thailand sambil melakukan deposit melalui Mandiri dengan kesempatan meraih kemenangan besar? Anda telah sampai di tempat yang tepat! Kami di WINNING303 siap memberikan Anda pengalaman bermain yang mengasyikkan dan menguntungkan. Mengapa Memilih WINNING303? WINNING303 telah dikenal sebagai salah satu platform terbaik untuk bermain slot dengan berbagai keunggulan yang kami tawarkan kepada para pemain kami. Berikut adalah beberapa alasan mengapa Anda harus memilih WINNING303: Slot Gacor dari Server Thailand Kami menyajikan koleksi slot gacor terbaik dari server Thailand yang pastinya akan memberikan Anda pengalaman bermain yang menarik dan menguntungkan. Nikmati berbagai jenis permainan slot dengan tingkat kemenangan yang tinggi dan jackpot yang menarik. Deposit Mudah Melalui Mandiri Kami memahami pentingnya kemudahan dalam bertransaksi bagi para pemain kami. Oleh karena itu, kami menyediakan layanan deposit melalui bank Mandiri, salah satu bank terbesar di Indonesia. Proses depositnya cepat, mudah, dan aman, sehingga Anda dapat langsung memulai petualangan bermain tanpa hambatan. Peluang Maxwin Besar Di WINNING303, kami selalu memberikan peluang untuk meraih kemenangan besar. Dengan berbagai promosi dan bonus menarik yang kami sediakan, Anda memiliki kesempatan untuk memenangkan hadiah-hadiah yang fantastis dan meraih maxwin dalam bermain slot.  
    • SLOT Ratubet77 adalah bocoran slot gacor rekomendasi dari Ratubet77 yang bisa anda temukan di SLOT Ratubet77. Situs SLOT Ratubet77 hari ini yang kami bagikan di sini adalah yang terbaik dan bersiaplah untuk mengalami sensasi tak terlupakan dalam permainan slot online. Temukan game SLOT Ratubet77 terbaik dengan 100 pilihan provider ternama yang dipercaya akan memberikan kepuasan dan kemenangan hari ini untuk meraih x500. RTP SLOT Ratubet77 merupakan SLOT Ratubet77 hari ini yang telah menjadi pilihan utama bagi pemain judi online di seluruh Indonesia. Setiap harinya jutaan pemain memasuki dunia maya untuk memperoleh hiburan seru dan kemenangan besar dalam bermain slot dengan adanya bocoran RTP SLOT Ratubet77. Tidak ada yang lebih menyenangkan daripada mengungguli mesin slot dan meraih jackpot x500 yang menggiurkan di situs SLOT Ratubet77 hari ini yang telah disediakan SLOT Ratubet77. Menangkan jackpot besar x500 rajanya maxwin dari segala slot dan raih kemenangan spektakuler di situs Ratubet77 terbaik 2024 adalah tempat yang menyediakan mesin slot dengan peluang kemenangan lebih tinggi daripada situs slot lainnya. Bagi anda yang mencari pengalaman judi slot paling seru dan mendebarkan, situs bo SLOT Ratubet77 terbaik 2024 adalah pilihan yang tepat. Jelajahi dunia slot online melalui situs SLOT Ratubet77 di link SLOT Ratubet77. DAFTAR SEKARANG DAFTAR SEKARANG DAFTAR SEKARANG
    • I am currently running the 1.20.1 Occultcraft modpack in Curseforge and am having numerous troubles making a mob farm with the apotheosis mod. When trying to modify the stats of the spawners specific stats such as the range, spawn count, and max entities reset to default after every spawn. When the spawners spawn boss mobs with certain attributes, that I'm not sure of, the building it is in explode even with mob griefing turned off. This has happened multiple times with varying sizes for the explosions. I was wonder if there is any way to disable these explosions from happening or disable boss abilities with something in the game. I also wanted to know a fix for the resetting stats on spawners and why this is happening.
    • SLOT Bank BSI adalah pilihan terbaik untuk Anda yang ingin merasakan sensasi bermain slot dengan layanan dari Bank BSI. Dengan keamanan terjamin, beragam pilihan permainan, kemudahan deposit via Bank BSI, dan berbagai bonus menarik, kami siap memberikan Anda pengalaman bermain yang tak terlupakan. Bergabunglah dengan kami sekarang dan mulailah petualangan seru Anda!    
  • Topics

×
×
  • Create New...

Important Information

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