Howto get/set nbt of item

Using mods I can get nbt tag/value of item with this code:

if ((item.hasTagCompound()) && (item.getTagCompound().hasKey("focus"))) {
                NBTTagCompound nbt = item.getTagCompound().getCompoundTag("focus");
                String[] bannedfocuses = {"thaumcraft:focus_hellbat", "thaumcraft:focus_primal"};
                if (Arrays.asList(bannedfocuses).contains(nbt.getString("id"))) {
                    player.addChatMessage(new ChatComponentText(EnumChatFormatting.DARK_RED + "This focus is disabled!"));
                    event.setCanceled(true);
                    
         }

}

item variable is ItemStack

Howto with sponge plugin?

We highly recommend you try not to use raw NBT in Sponge. NBT can change at any time, the Sponge API is meant to be there to provide a layer on top of NBT.

If you absolutely need access to NBT, you can use item.toContainer() and use the methods on DataViews in a very similar fashion to NBT. Alternatively, you can cast any of the Sponge-type objects to their NMS equivalents, eg (net.minecraft.entity.Entity) mySpongeEntity.

Usually what we recommend is creating a compat module that sits between a mod like thaumcraft, and your plugin.

The mod implements native API features (primarily data manipulators) for mod concepts, and plugs them into the Sponge systems, allowing you to do something like this:

List<Focus> bannedFoci = ImmutableList.of(Focuses.HELLBAT, Focuses.PRIMAL);
item.get(ThaumcraftKeys.FOCUS).ifPresent(focuses -> {
    if(focuses.filter(bannedFoci::contains).isEmpty()) {
        player.sendMessage(Texts.of(ChatColors.DARK_RED, "This focus is disabled!");
    }
});

There is many examples of this for vanilla features in SpongeCommon’s data implementations. You can also create/mixin mod enums, create/mixin mod entities, etc.

2 Likes

@gabizou is making a plugin called ThaumicSponge, which is a bridge between Sponge and Thaumcraft.

Adding onto this - the custom NBT tag used by the mod item/entity, if set, will be available with the query “UnsafeData” within the main DataContainer.