Skip to content

DataComponentType

Aram edited this page Sep 11, 2025 · 1 revision

Using DataComponentType with Cache Objects

Overview

Each cache object in BlueLib also have a dedicated DataComponentType, which allows the cache to be directly attached to game objects such as ItemStack, entities, or custom containers.

This provides:

  • Persistent storage for your cache inside Minecraft objects.
  • Easy access via code without manually reading/writing NBT.
  • Integration with your CODEC system for automatic serialization.

Implementation Example

Using RGBAColorCache as an example:

import software.bluelib.api.datapack.DataComponentType;
import org.jetbrains.annotations.NotNull;
import java.util.function.Supplier;

public record RGBAColorCache(Integer red, Integer green, Integer blue, Integer alpha) {
    public static final DataComponentType<RGBAColorCache> RGBA_COLOR_DATA =
            DataComponentType.<RGBAColorCache>builder()
                    .persistent(CODEC)
                    .build();
}

How to Use in Code

Once the DataComponentType is registered, you can attach the cache to objects like ItemStack:

ItemStack stack = new ItemStack(Items.DIAMOND);
RGBAColorCache cache = new RGBAColorCache(255, 128, 64, 200);

stack.set(RGBAColorCache.RGBA_COLOR_DATA, cache);

RGBAColorCache storedCache = stack.get(RGBAColorCache.RGBA_COLOR_DATA);

How It Works

  1. DataComponentType Creation

    • Built with a persistent CODEC, linking serialization/deserialization to Minecraft's NBT system.
    • Each cache type has its own DataComponentType, ensuring type safety.
  2. Registration

    • Use a registerData method or similar system to ensure the type is globally available.
  3. Attaching to Objects

    • You can set and get the cache directly on objects like ItemStack, entities, or other supported containers.
    • The underlying CODEC handles all serialization and deserialization automatically.

Key Points

  • Every cache type can have its own DataComponentType.
  • DataComponentTypes simplify attaching persistent cache data to objects.
  • Works seamlessly with CODECs and CompoundTags for safe and consistent data handling.
  • Enables clean and readable code without manual NBT management.

Clone this wiki locally