User Tools

Site Tools


tutorial:blockentity_modify_data

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
tutorial:blockentity_modify_data [2024/08/26 00:31] solidblocktutorial:blockentity_modify_data [2025/04/01 12:48] (current) – [Some notes about NbtCompound] solidblock
Line 1: Line 1:
 ====== Modify BlockEntity data ====== ====== Modify BlockEntity data ======
  
-===== Introduction =====+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]]. Now we try to modify the block entity data. The ''DemoBlockEntity'' class should be written like this:+===== Some notes about NbtCompound ===== 
 + 
 +Since 1.21.5, methods of ''NbtCompound'' have been changed. The getter methods return ''Optional'' objects, unless you specify another parameter as a default value used when the field does not exist. For example: 
 + 
 +<code java> 
 +// no default value specified, returns Optional 
 +Optional<Integer> value = nbt.getInt("value"); // not OptionalInt 
 + 
 +// default value specified, returns the default value when the field does not exist 
 +int value = nbt.getInt("value", 1000); 
 +</code> 
 + 
 +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<NbtCompound> config = nbt.getCompound("config"); 
 + 
 +// when the field does not exist, returns an empty compound 
 +NbtCompound config = nbt.getCompoundOrEmpty("config"); 
 +</code> 
 + 
 +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 ''contains'' method beforehand. For example: 
 +<code java> 
 +// returns 0 if the field does not exist: 
 +int value = nbt.getInt("value"); 
 + 
 +// returns an empty compound when the field does not exist: 
 +NbtCompound config = nbt.getCompound("config"); 
 +</code> 
 + 
 +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("Id", Identifier.CODEC, Identifier.of("tutorial""example_id")); 
 +Optional<Identifier> id = nbt.get("Id", Identifier.CODEC); 
 +</code> 
 + 
 +<code java> 
 +NbtCompound nbt = new NbtCompound(); 
 +// have to use the RegistryOps since an item is registry entry 
 +nbt.copyFromCodec(ItemStack.MAP_CODEC, wrapperLookup.getOps(NbtOps.INSTANCE), new ItemStack(Items.WHEAT)); 
 +Optional<ItemStack> stack = nbt.decode(ItemStack.MAP_CODEC, wrapperLookup.getOps(NbtOps.INSTANCE)); 
 +</code> 
 + 
 +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://fabricmc.net/2025/03/24/1215.html|Fabric for Minecraft 1.21.5]]. 
 +===== Serializing Data ===== 
 + 
 +If you want to store any data in your ''BlockEntity'', you will need to save and load it, or it will only be held while the ''BlockEntity'' is loaded, and the data will reset whenever you come back to it. Luckily, saving and loading is quite simple - you only need to override ''writeNbt()'' and ''readNbt()''.  
 + 
 +''writeNbt()'' modifies the parameter ''nbt'', which should contain all of the data in your block entity. It usually does not modify the block entity object itself. The NBT is saved to the disk, and if you need to sync your block entity data with clients, also sent through packets. 
 + 
 +In older versions, it was very important to call ''super.writeNbt'', which saves the position and id of the block entity to the nbt. Without this, any further data you try and save would be lost as it is not associated with a position and ''BlockEntityType''. However, latest versions do not require it, as they will be handled through ''createNbt()'' method. 
 + 
 +Knowing this, the example below demonstrates saving an integer from your ''BlockEntity'' to the nbt. In the example, the integer is saved under the key ''"number"'' - you can replace this with any string, but you can only have one entry for each key in your nbt, and you will need to remember the key in order to read the data later. 
 + 
 +<code java DemoBlockEntity.java> 
 +public class DemoBlockEntity extends BlockEntity { 
 + 
 +    // Store the current value of the number 
 +    private int number = 0; 
 +    
 +    public DemoBlockEntity(BlockPos pos, BlockState state) { 
 +        super(TutorialBlockEntityTypes.DEMO_BLOCK, pos, state); 
 +    } 
 +    
 +    // Serialize the BlockEntity 
 +    @Override 
 +    public void writeNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registries) { 
 +        // Save the current value of the number to the nbt 
 +        nbt.putInt("number", number); 
 + 
 +        super.writeNbt(nbt, registries); 
 +    } 
 +
 +</code> 
 + 
 +In order to read the data, you will also need to override ''readNbt''. This method is the opposite of ''writeNbt'' - instead of saving your data to a ''NBTCompound'', you are given the nbt data which you saved earlier, enabling you to retrieve any data that you need. It modifies the block entity object itself, instead of the ''nbt''. To read the number we saved earlier in the nbt, see the example below. 
 + 
 +<code java> 
 +    // Deserialize the BlockEntity 
 +    @Override 
 +    public void readNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registries) { 
 +        super.readNbt(nbt, registries); 
 +         
 +        number = nbt.getInt("number", 0); 
 +    } 
 +</code> 
 + 
 +To get the NBT data for the block entity, call ''createNbt(registries)''. It will also handle some data like position and components. 
 + 
 +For old versions, calling ''super.readNbt()'' and ''super.writeNbt()'' was essential, because handling data such as positions is required. In old versions, if ''createNbt'' does not exist, try ''writeNbt(new NbtCompound())''
 + 
 +===== Sync data from server to client ===== 
 +The data is read in the server world usually. Most data are not needed by the client, for example, your client does not need to know what's in the chest or furnace, until you open the GUI. But for some block entities, such as signs and banners, you have to inform the client of the data of the block entity, for example, for rendering. 
 + 
 +For version 1.17.1 and below, implement ''BlockEntityClientSerializable'' from the Fabric API. This class provides the ''fromClientTag'' and ''toClientTag'' methods, which work much the same as the previously discussed ''readNbt'' and ''writeNbt'' methods, except that they are used specifically for sending to and receiving data on the client. You may simply call ''readNbt'' and ''writeNbt'' in the ''fromClientTag'' and ''toClientTag'' methods. 
 + 
 +For version 1.18 and above, override ''toUpdatePacket'' and ''toInitialChunkDataNbt'': 
 +<code java> 
 +  @Nullable 
 +  @Override 
 +  public Packet<ClientPlayPacketListener> toUpdatePacket() { 
 +    return BlockEntityUpdateS2CPacket.create(this); 
 +  } 
 + 
 +  @Override 
 +  public NbtCompound toInitialChunkDataNbt(RegistryWrapper.WrapperLookup registryLookup) { 
 +    return createNbt(registryLookup); 
 +  } 
 +</code>
  
 <code java DemoBlockEntity.class> <code java DemoBlockEntity.class>
Line 11: Line 122:
    
     public DemoBlockEntity(BlockPos pos, BlockState state) {     public DemoBlockEntity(BlockPos pos, BlockState state) {
-        super(ExampleMod.DEMO_BLOCK_ENTITY, pos, state);+        super(TutorialBlockEntityTypes.DEMO_BLOCK, pos, state);
     }     }
    
     @Override     @Override
-    public void writeNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) {+    public void writeNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registries) {
         nbt.putInt("number", number);         nbt.putInt("number", number);
    
-        super.writeNbt(nbt, registryLookup);+        super.writeNbt(nbt, registries);
     }     }
          
     @Override     @Override
-    public void readNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) { +    public void readNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registries) { 
-        super.readNbt(nbt);+        super.readNbt(nbt, registries);
    
-        number = nbt.getInt("number", registryLookup);+        // for versions before 1.21.5, use nbt.getInt("number"); 
 +        number = nbt.getInt("number", 0);
     }     }
 } }
 </code> </code>
  
-Make sure the ''number'' field is **public**, as we are going to change it in the ''DemoBlock'' class. You could also make getter and setter methods, but we just expose the field here for simplicity..+Make sure the ''number'' field is **public**, as we are going to change it in the ''DemoBlock'' class. You could also make getter and setter methods, but we just expose the field here for simplicity.
  
 ===== Modifying the data ===== ===== Modifying the data =====
Line 48: Line 160:
                 demoBlockEntity.number++;                 demoBlockEntity.number++;
                 player.sendMessage(Text.literal("Number is " + demoBlockEntity.number));                 player.sendMessage(Text.literal("Number is " + demoBlockEntity.number));
 +                demoBlockEntity.markDirty();
             }             }
         }         }
                  
-        return ActionResult.success(world.isClient);+        return ActionResult.SUCCESS;
     }     }
 } }
 +</code>
 +
 +The method ''markDirty()'' should be called whenever the block entity is modified. This will mark the position "dirty" to force the ''writeNbt'' method to be called when the world is next saved. As a general rule of thumb, simply call ''markDirty()'' whenever you modify any custom variable in your ''BlockEntity'' class, otherwise after you exit and re-enter the world, the block entity appears as if the modification had not been done.
 +
 +If you want clients to know the update (for example, they may be need to render, or pick-stack without holding ''Ctrl''), add an extra line after the ''markDirty'' call, so that the client will know the block entity has been changed:
 +<code java>
 +                world.updateListeners(pos, state, state, 0);
 </code> </code>
  
 ===== Using data components ===== ===== Using data components =====
  
-Since 1.20.5, you can also use data components to store data. In this case, as data components have codecs that can serialize and deserialize themselves, you do not need to write ''readNbt'' and ''writeNbt'' methods for them.+Since 1.20.5, you can also use data components to store data. This is required if you want to write the data into item stacks. You still need to write ''readNbt'' and ''writeNbt'' methods for them to save the block entities correctly.
  
-If you want to have try, //remove// the ''readNbt'' and ''writeNbt'' methods before. And then create a data component type for it:+Create data component type in a separate class ''TutorialDataComponentTypes'' for it. More information about registering data components can be seen in [[https://docs.fabricmc.net/develop/items/custom-data-components|Fabric Docs page]].
  
-<code java ExampleMod.java> +<code java TutorialDataComponentTypes.java> 
-    public static final ComponentType<Integer> NUMBER = Registry.register(Registries.DATA_COMPONENT_TYPE, Identifier.of("tutorial", "number"), ComponentType.<Integer>builder().codec(Codec.INT).packetCodec(PacketCodecs.INTEGER).build());+public class TutorialDataComponentTypes { 
 +  public static final ComponentType<Integer> NUMBER = register("number", builder -> builder 
 +      .codec(Codec.INT) 
 +      .packetCodec(PacketCodecs.INTEGER)); 
 + 
 +  public static <T> ComponentType<T> register(String path, UnaryOperator<ComponentType.Builder<T>> builderOperator) { 
 +    return Registry.register(Registries.DATA_COMPONENT_TYPE, Identifier.of("tutorial", path), builderOperator.apply(ComponentType.builder()).build()); 
 +  } 
 + 
 +  public static void initialize() { 
 +  } 
 +}
 </code> </code>
  
-> :!: Here for simplicity, we just place them in the ''ModInitializer''When actually developing mods, if you have multiple data component types, consider creating a separate class to store data components.+Remember to refer to the method in the ''ModInitializer''
 +<code java ExampleMod.java> 
 +public class ExampleMod implements ModInitializer { 
 +  [...] 
 +   
 +  @Override 
 +  public static void onInitialize() { 
 +    [..] 
 +    TutorialDataComponentTypes.initialize(); 
 +  } 
 +
 +</code>
  
 And then in the block entity: And then in the block entity:
  
 <code java DemoBlockEntity.java> <code java DemoBlockEntity.java>
-  // removed the `readNbt` and `writeNbt` methods. 
- 
   @Override   @Override
   protected void readComponents(ComponentsAccess components) {   protected void readComponents(ComponentsAccess components) {
Line 84: Line 224:
     componentMapBuilder.add(ExampleMod.NUMBER, number);     componentMapBuilder.add(ExampleMod.NUMBER, number);
   }   }
-</code> 
  
-Now these components can also be stored normally. If you pick stack (which means press the mouse wheel to the block write pressing ''Ctrl''), the components will be transferred to the stack.+  @Override 
 +  public void removeFromCopiedStackNbt(NbtCompound nbt
 +    nbt.remove("number"); 
 +  } 
 +</code>
  
-In some cases, you can also retain the ''readNbt'' and ''writeNbt'' methodsand override ''removeFromCopiedStackNbt'' method to remove the ''%%"number"%%'' field from the nbt.+The usage of ''removeFromCopiedStackNbt'' iswhen copying item stacks, as the components are already copied, the nbts are no longer needed. If you pick stack (which means press the mouse wheel to the block write pressing ''Ctrl''), the components will be transferred to the stack. If you need to transfer the components when pick blocks even if you do not hold ''Ctrl'' (like the behavior of vanilla banner blocks), see [[blockentity_sync_itemstack]].
tutorial/blockentity_modify_data.1724632268.txt.gz · Last modified: 2024/08/26 00:31 by solidblock