Skip to content

Serializable Components

CmdrNorthpaw edited this page Apr 15, 2021 · 2 revisions

Now that you've set up KInventory, you'll need to learn a little about what makes it tick before you can use it.

SerializableInventory

To make an inventory serializable, you make a class extending SerializableInventory<T>. Here, T is any type that implements Inventory. SerializableInventory has one abstract method, toInventory(), which converts the serializable inventory into an Inventory of type T. Because every inventory is different, it's up to the implementing class to decide how to convert themselves into the inventory they've chosen to be able to serialize. Note that you do not need to actually implement Inventory to make an implementation of SerializableInventory, (I tried that, it was messy), you just need to know how to turn into a class that does.

SerializableItemStack

Aside from being able to convert into a proper inventory, one property that every SerializableInventory shares is items, a List of SerializableItemStacks. SerializableItemStack is a fairly simple class that stores the registry key of an item, the amount of that item in the stack, and a string representation of any NBT data that stack happened to have on it. Since the removal of metadata in 1.12, everything is stored in NBT, so this allows you to completely recreate ItemStacks from simple JSON. To help make creating them easier, SerializableItemStack's companion object includes an extension function for ItemStacks that will convert them into SerializableItemStacks for you.

While the registry key, count and NBT data are usually enough to create any ItemStack you might need, I realize that sometimes you need to store a little more than that. To that end, I've made SerializableItemStack an open class, so that you can extend it with any extra information you might want. Armour, for example, has its own extension class, SerializableArmourPiece, which also stores the EquipmentSlotType of the armour. Do note that because of the way kotlinx.serialization works, you have to have values in the constructor, (so like val whatever: String instead of whatever: String) and these values have to have different names from the ones in the class below. I also suggest making them private so that your users don't get confused over which to use.

SerializableInventoryCompanion

Finally, I would like to briefly draw your attention to SerializableInventoryCompanion<I, S>. While, you can, of course, use it anywhere you like, it's designed to be implemented by the companion object of a SerializableInventory, and provides a method to convert an inventory into its serializable form. You don't have to implement it if you don't want to but you will need it if you'd like automatic surrogate serializer creation, which is discussed later.

Clone this wiki locally