tutorial:blockentity_modify_data
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
tutorial:blockentity_modify_data [2025/04/01 12:30] – update solidblock | tutorial:blockentity_modify_data [2025/04/01 12:48] (current) – [Some notes about NbtCompound] solidblock | ||
---|---|---|---|
Line 3: | Line 3: | ||
In the previous tutorial, we have created a [[blockentity|block entity]]. But they are too boring as they do not have any data. Therefore, we try to add some data to it, and define ways of serializing and deserializing data. | In the previous tutorial, we have created a [[blockentity|block entity]]. But they are too boring as they do not have any data. Therefore, we try to add some data to it, and define ways of serializing and deserializing data. | ||
+ | ===== Some notes about NbtCompound ===== | ||
+ | |||
+ | Since 1.21.5, methods of '' | ||
+ | |||
+ | <code java> | ||
+ | // no default value specified, returns Optional | ||
+ | Optional< | ||
+ | |||
+ | // default value specified, returns the default value when the field does not exist | ||
+ | int value = nbt.getInt(" | ||
+ | </ | ||
+ | |||
+ | For collection types, such as compounds and lists, an empty object can be returned as a default value, for example: | ||
+ | <code java> | ||
+ | // no default value specified, returns Optional | ||
+ | Optional< | ||
+ | |||
+ | // when the field does not exist, returns an empty compound | ||
+ | NbtCompound config = nbt.getCompoundOrEmpty(" | ||
+ | </ | ||
+ | |||
+ | In versions before 1.21.5, they return zero or empty values. If you need to specify a default value, you need to judge with '' | ||
+ | <code java> | ||
+ | // returns 0 if the field does not exist: | ||
+ | int value = nbt.getInt(" | ||
+ | |||
+ | // returns an empty compound when the field does not exist: | ||
+ | NbtCompound config = nbt.getCompound(" | ||
+ | </ | ||
+ | |||
+ | Besides, since 1.21.5, the whole NBT compound and its fields can be decoded directly with [[codec]]s, such as: | ||
+ | <code java> | ||
+ | NbtCompound nbt = new NbtCompound(); | ||
+ | nbt.put(" | ||
+ | Optional< | ||
+ | </ | ||
+ | |||
+ | <code java> | ||
+ | NbtCompound nbt = new NbtCompound(); | ||
+ | // have to use the RegistryOps since an item is a registry entry | ||
+ | nbt.copyFromCodec(ItemStack.MAP_CODEC, | ||
+ | Optional< | ||
+ | </ | ||
+ | |||
+ | Besides, since 1.21.5, lists support mixing elements of different types. In previous versions, mixing elements of different types in a list results in exceptions. | ||
+ | |||
+ | More information about NBT changes, see [[https:// | ||
===== Serializing Data ===== | ===== Serializing Data ===== | ||
tutorial/blockentity_modify_data.1743510615.txt.gz · Last modified: 2025/04/01 12:30 by solidblock