Skip to content

How to store data on a player or entity in a Minecraft mod

An attachment is a value stuck onto an entity, a block entity, a chunk or a level, saved with it. From 1.20.4, NeoForge registers an AttachmentType in a DeferredRegister with a default and a Codec to save it, and reads and writes with entity.getData and setData; Fabric API uses AttachmentRegistry.createPersistent(id, codec), then getAttachedOrElse and setAttached. Older versions have no attachments: Fabric keeps the value in the world’s SavedData, Forge uses a capability (see the notes). This is how you add ‘mana’ or a counter to a player. The value is not synced to the client by itself.

Works on Minecraft 1.20.1 to 26.3 on NeoForge; Minecraft 1.16.5 to 26.3 on Fabric; Minecraft 1.16.5 to 1.20.1 on Forge; Minecraft 1.12.2 on Forge. Each example was compiled against its loader and version before it shipped in Linen.

  1. Register an attachment type with a default value and a Codec (on older versions, set up the SavedData or capability).
  2. Read it with getData or getAttachedOrElse.
  3. Write it back with setData or setAttached.
  4. Join twice and see the number rise; restart and it stays.

The example mod is examplemod in the package com.example.examplemod. Use your own mod id and package.

Uses:

  • SavedData
  • DimensionDataStorage.computeIfAbsent
  • ServerPlayConnectionEvents.JOIN

Fabric API got data attachments in 1.20.4. Before that, keep the number in the world’s SavedData, keyed by the player’s UUID (computeIfAbsent takes the load function and a supplier).

src/main/java/com/example/examplemod/registry/JoinMemoryAttach.java

package com.example.examplemod.registry;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.saveddata.SavedData;
// A number saved for each player, in the world's saved data (this Fabric API has no attachments yet). Every join adds 1 and the player is told.
public class JoinMemoryAttach extends SavedData {
private final Map<UUID, Integer> joins = new HashMap<>();
public static JoinMemoryAttach load(CompoundTag tag) {
JoinMemoryAttach data = new JoinMemoryAttach();
for (String id : tag.getAllKeys()) {
data.joins.put(UUID.fromString(id), tag.getInt(id));
}
return data;
}
@Override
public CompoundTag save(CompoundTag tag) {
joins.forEach((id, count) -> tag.putInt(id.toString(), count));
return tag;
}
public int addJoin(UUID player) {
setDirty();
return joins.merge(player, 1, Integer::sum);
}
public static JoinMemoryAttach get(MinecraftServer server) {
return server.overworld().getDataStorage().computeIfAbsent(JoinMemoryAttach::load, JoinMemoryAttach::new, "examplemod_join_memory");
}
// Called from the mod's onInitialize.
public static void register() {
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
int count = get(server).addJoin(handler.getPlayer().getUUID());
handler.getPlayer().sendSystemMessage(Component.literal("Your joins: " + count));
});
}
}

In your main mod class, inside onInitialize:

JoinMemoryAttach.register();

Uses:

  • CapabilityManager.get
  • ICapabilitySerializable
  • AttachCapabilitiesEvent
  • RegisterCapabilitiesEvent
  • PlayerEvent.Clone

Forge 1.20.1 has no data attachments: per-player data is a capability, attached in AttachCapabilitiesEvent. For one small value, Player#getPersistentData() (an NBT tag that is saved with the player) is a shorter option.

src/main/java/com/example/examplemod/registry/JoinMemoryAttach.java

package com.example.examplemod.registry;
import com.example.examplemod.ExampleMod;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityToken;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.IEventBus;
// A number saved on each player (a Forge capability). Every join adds 1 and the player is told.
public final class JoinMemoryAttach {
public static final Capability<Joins> JOINS = CapabilityManager.get(new CapabilityToken<>() {
});
private static final ResourceLocation ID = new ResourceLocation(ExampleMod.MOD_ID, "join_memory");
private JoinMemoryAttach() {
}
// The data itself.
public static class Joins {
private int count;
public int increment() {
return ++count;
}
}
// Holds one Joins per player and saves it with the player.
private static class Provider implements ICapabilitySerializable<CompoundTag> {
private final Joins joins = new Joins();
private final LazyOptional<Joins> holder = LazyOptional.of(() -> joins);
@Override
public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
return cap == JOINS ? holder.cast() : LazyOptional.empty();
}
@Override
public CompoundTag serializeNBT() {
CompoundTag tag = new CompoundTag();
tag.putInt("joins", joins.count);
return tag;
}
@Override
public void deserializeNBT(CompoundTag tag) {
joins.count = tag.getInt("joins");
}
}
// Called from the mod's constructor.
public static void register(IEventBus modBus) {
modBus.addListener(JoinMemoryAttach::onRegisterCapabilities);
MinecraftForge.EVENT_BUS.addGenericListener(Entity.class, JoinMemoryAttach::onAttach);
MinecraftForge.EVENT_BUS.addListener(JoinMemoryAttach::onClone);
MinecraftForge.EVENT_BUS.addListener(JoinMemoryAttach::onLogin);
}
private static void onRegisterCapabilities(RegisterCapabilitiesEvent event) {
event.register(Joins.class);
}
private static void onAttach(AttachCapabilitiesEvent<Entity> event) {
if (event.getObject() instanceof Player) {
event.addCapability(ID, new Provider());
}
}
// Keeps the number when a player dies and respawns.
private static void onClone(PlayerEvent.Clone event) {
if (event.isWasDeath()) {
event.getOriginal().reviveCaps();
event.getOriginal().getCapability(JOINS).ifPresent(old ->
event.getEntity().getCapability(JOINS).ifPresent(now -> now.count = old.count));
event.getOriginal().invalidateCaps();
}
}
private static void onLogin(PlayerEvent.PlayerLoggedInEvent event) {
if (event.getEntity() instanceof ServerPlayer player) {
player.getCapability(JOINS).ifPresent(joins ->
player.sendSystemMessage(Component.literal("Your joins: " + joins.increment())));
}
}
}

In your main mod class, inside <init>:

JoinMemoryAttach.register(modEventBus);

Uses:

  • CapabilityManager.get
  • ICapabilitySerializable
  • AttachCapabilitiesEvent
  • RegisterCapabilitiesEvent
  • PlayerEvent.Clone

NeoForge 1.20.2 has no data attachments (they came with 1.20.4): per-player data is a capability, attached in AttachCapabilitiesEvent. For one small value, Player#getPersistentData() (an NBT tag that is saved with the player) is a shorter option.

src/main/java/com/example/examplemod/registry/JoinMemoryAttach.java

package com.example.examplemod.registry;
import com.example.examplemod.ExampleMod;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.common.capabilities.Capability;
import net.neoforged.neoforge.common.capabilities.CapabilityManager;
import net.neoforged.neoforge.common.capabilities.CapabilityToken;
import net.neoforged.neoforge.common.capabilities.ICapabilitySerializable;
import net.neoforged.neoforge.common.capabilities.RegisterCapabilitiesEvent;
import net.neoforged.neoforge.common.util.LazyOptional;
import net.neoforged.neoforge.event.AttachCapabilitiesEvent;
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
import net.neoforged.bus.api.IEventBus;
// A number saved on each player (a NeoForge capability). Every join adds 1 and the player is told.
public final class JoinMemoryAttach {
public static final Capability<Joins> JOINS = CapabilityManager.get(new CapabilityToken<>() {
});
private static final ResourceLocation ID = new ResourceLocation(ExampleMod.MOD_ID, "join_memory");
private JoinMemoryAttach() {
}
// The data itself.
public static class Joins {
private int count;
public int increment() {
return ++count;
}
}
// Holds one Joins per player and saves it with the player.
private static class Provider implements ICapabilitySerializable<CompoundTag> {
private final Joins joins = new Joins();
private final LazyOptional<Joins> holder = LazyOptional.of(() -> joins);
@Override
public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
return cap == JOINS ? holder.cast() : LazyOptional.empty();
}
@Override
public CompoundTag serializeNBT() {
CompoundTag tag = new CompoundTag();
tag.putInt("joins", joins.count);
return tag;
}
@Override
public void deserializeNBT(CompoundTag tag) {
joins.count = tag.getInt("joins");
}
}
// Called from the mod's constructor.
public static void register(IEventBus modBus) {
modBus.addListener(JoinMemoryAttach::onRegisterCapabilities);
NeoForge.EVENT_BUS.addGenericListener(Entity.class, JoinMemoryAttach::onAttach);
NeoForge.EVENT_BUS.addListener(JoinMemoryAttach::onClone);
NeoForge.EVENT_BUS.addListener(JoinMemoryAttach::onLogin);
}
private static void onRegisterCapabilities(RegisterCapabilitiesEvent event) {
event.register(Joins.class);
}
private static void onAttach(AttachCapabilitiesEvent<Entity> event) {
if (event.getObject() instanceof Player) {
event.addCapability(ID, new Provider());
}
}
// Keeps the number when a player dies and respawns.
private static void onClone(PlayerEvent.Clone event) {
if (event.isWasDeath()) {
event.getOriginal().reviveCaps();
event.getOriginal().getCapability(JOINS).ifPresent(old ->
event.getEntity().getCapability(JOINS).ifPresent(now -> now.count = old.count));
event.getOriginal().invalidateCaps();
}
}
private static void onLogin(PlayerEvent.PlayerLoggedInEvent event) {
if (event.getEntity() instanceof ServerPlayer player) {
player.getCapability(JOINS).ifPresent(joins ->
player.sendSystemMessage(Component.literal("Your joins: " + joins.increment())));
}
}
}

In your main mod class, inside <init>:

JoinMemoryAttach.register(modEventBus);

Uses:

  • AttachmentRegistry.createPersistent
  • AttachmentTarget.getAttachedOrElse
  • AttachmentTarget.setAttached

src/main/java/com/example/examplemod/registry/JoinMemoryAttach.java

package com.example.examplemod.registry;
import com.mojang.serialization.Codec;
import net.fabricmc.fabric.api.attachment.v1.AttachmentRegistry;
import net.fabricmc.fabric.api.attachment.v1.AttachmentType;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
// A number saved on each player (Fabric API attachments). Every join adds 1 and the player is told.
public final class JoinMemoryAttach {
public static final AttachmentType<Integer> JOINS = AttachmentRegistry.createPersistent(
new ResourceLocation("examplemod", "join_memory"), Codec.INT);
private JoinMemoryAttach() {
}
// Called from the mod's onInitialize.
public static void register() {
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
int joins = handler.getPlayer().getAttachedOrElse(JOINS, 0) + 1;
handler.getPlayer().setAttached(JOINS, joins);
handler.getPlayer().sendSystemMessage(Component.literal("Your joins: " + joins));
});
}
}

In your main mod class, inside onInitialize:

JoinMemoryAttach.register();

Uses:

  • SavedData
  • DimensionDataStorage.computeIfAbsent
  • ServerPlayConnectionEvents.JOIN

Fabric API got data attachments in 1.20.4. Before that, keep the number in the world’s SavedData, keyed by the player’s UUID (with SavedData.Factory).

src/main/java/com/example/examplemod/registry/JoinMemoryAttach.java

package com.example.examplemod.registry;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.saveddata.SavedData;
// A number saved for each player, in the world's saved data (this Fabric API has no attachments yet). Every join adds 1 and the player is told.
public class JoinMemoryAttach extends SavedData {
public static final SavedData.Factory<JoinMemoryAttach> FACTORY = new SavedData.Factory<>(JoinMemoryAttach::new, JoinMemoryAttach::load, null);
private final Map<UUID, Integer> joins = new HashMap<>();
public static JoinMemoryAttach load(CompoundTag tag) {
JoinMemoryAttach data = new JoinMemoryAttach();
for (String id : tag.getAllKeys()) {
data.joins.put(UUID.fromString(id), tag.getInt(id));
}
return data;
}
@Override
public CompoundTag save(CompoundTag tag) {
joins.forEach((id, count) -> tag.putInt(id.toString(), count));
return tag;
}
public int addJoin(UUID player) {
setDirty();
return joins.merge(player, 1, Integer::sum);
}
public static JoinMemoryAttach get(MinecraftServer server) {
return server.overworld().getDataStorage().computeIfAbsent(FACTORY, "examplemod_join_memory");
}
// Called from the mod's onInitialize.
public static void register() {
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
int count = get(server).addJoin(handler.getPlayer().getUUID());
handler.getPlayer().sendSystemMessage(Component.literal("Your joins: " + count));
});
}
}

In your main mod class, inside onInitialize:

JoinMemoryAttach.register();

Fabric 1.21 to 1.21.1, Fabric 1.21.2 to 1.21.10

Section titled “Fabric 1.21 to 1.21.1, Fabric 1.21.2 to 1.21.10”

Uses:

  • AttachmentRegistry.createPersistent
  • AttachmentTarget.getAttachedOrElse
  • AttachmentTarget.setAttached

src/main/java/com/example/examplemod/registry/JoinMemoryAttach.java

package com.example.examplemod.registry;
import com.mojang.serialization.Codec;
import net.fabricmc.fabric.api.attachment.v1.AttachmentRegistry;
import net.fabricmc.fabric.api.attachment.v1.AttachmentType;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
// A number saved on each player (Fabric API attachments). Every join adds 1 and the player is told.
public final class JoinMemoryAttach {
public static final AttachmentType<Integer> JOINS = AttachmentRegistry.createPersistent(
ResourceLocation.fromNamespaceAndPath("examplemod", "join_memory"), Codec.INT);
private JoinMemoryAttach() {
}
// Called from the mod's onInitialize.
public static void register() {
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
int joins = handler.getPlayer().getAttachedOrElse(JOINS, 0) + 1;
handler.getPlayer().setAttached(JOINS, joins);
handler.getPlayer().sendSystemMessage(Component.literal("Your joins: " + joins));
});
}
}

In your main mod class, inside onInitialize:

JoinMemoryAttach.register();

NeoForge 1.20.4 to 1.21.1, NeoForge 1.21.2 to 1.21.5

Section titled “NeoForge 1.20.4 to 1.21.1, NeoForge 1.21.2 to 1.21.5”

Uses:

  • AttachmentType.builder
  • NeoForgeRegistries.ATTACHMENT_TYPES
  • IAttachmentHolder.getData
  • IAttachmentHolder.setData

src/main/java/com/example/examplemod/registry/JoinMemoryAttach.java

package com.example.examplemod.registry;
import com.example.examplemod.ExampleMod;
import com.mojang.serialization.Codec;
import java.util.function.Supplier;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.neoforge.attachment.AttachmentType;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
import net.neoforged.neoforge.registries.DeferredRegister;
import net.neoforged.neoforge.registries.NeoForgeRegistries;
// A number saved on each player (NeoForge data attachment). Every join adds 1 and the player is told.
public final class JoinMemoryAttach {
private static final DeferredRegister<AttachmentType<?>> ATTACHMENTS = DeferredRegister.create(NeoForgeRegistries.ATTACHMENT_TYPES, ExampleMod.MOD_ID);
public static final Supplier<AttachmentType<Integer>> JOINS = ATTACHMENTS.register("join_memory",
() -> AttachmentType.builder(() -> 0).serialize(Codec.INT).copyOnDeath().build());
private JoinMemoryAttach() {
}
// Called from the mod's constructor.
public static void register(IEventBus modBus) {
ATTACHMENTS.register(modBus);
NeoForge.EVENT_BUS.addListener(JoinMemoryAttach::onLogin);
}
private static void onLogin(PlayerEvent.PlayerLoggedInEvent event) {
if (event.getEntity() instanceof ServerPlayer player) {
int joins = player.getData(JOINS.get()) + 1;
player.setData(JOINS.get(), joins);
player.sendSystemMessage(Component.literal("Your joins: " + joins));
}
}
}

In your main mod class, inside <init>:

JoinMemoryAttach.register(modEventBus);

Uses:

  • AttachmentType.builder
  • NeoForgeRegistries.ATTACHMENT_TYPES
  • IAttachmentHolder.getData
  • IAttachmentHolder.setData

src/main/java/com/example/examplemod/registry/JoinMemoryAttach.java

package com.example.examplemod.registry;
import com.example.examplemod.ExampleMod;
import com.mojang.serialization.Codec;
import java.util.function.Supplier;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.neoforge.attachment.AttachmentType;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
import net.neoforged.neoforge.registries.DeferredRegister;
import net.neoforged.neoforge.registries.NeoForgeRegistries;
// A number saved on each player (NeoForge data attachment). Every join adds 1 and the player is told.
public final class JoinMemoryAttach {
private static final DeferredRegister<AttachmentType<?>> ATTACHMENTS = DeferredRegister.create(NeoForgeRegistries.ATTACHMENT_TYPES, ExampleMod.MOD_ID);
public static final Supplier<AttachmentType<Integer>> JOINS = ATTACHMENTS.register("join_memory",
() -> AttachmentType.builder(() -> 0).serialize(Codec.INT.fieldOf("joins")).copyOnDeath().build());
private JoinMemoryAttach() {
}
// Called from the mod's constructor.
public static void register(IEventBus modBus) {
ATTACHMENTS.register(modBus);
NeoForge.EVENT_BUS.addListener(JoinMemoryAttach::onLogin);
}
private static void onLogin(PlayerEvent.PlayerLoggedInEvent event) {
if (event.getEntity() instanceof ServerPlayer player) {
int joins = player.getData(JOINS.get()) + 1;
player.setData(JOINS.get(), joins);
player.sendSystemMessage(Component.literal("Your joins: " + joins));
}
}
}

In your main mod class, inside <init>:

JoinMemoryAttach.register(modEventBus);

Uses:

  • AttachmentRegistry.createPersistent
  • AttachmentTarget.getAttachedOrElse
  • AttachmentTarget.setAttached

src/main/java/com/example/examplemod/registry/JoinMemoryAttach.java

package com.example.examplemod.registry;
import com.mojang.serialization.Codec;
import net.fabricmc.fabric.api.attachment.v1.AttachmentRegistry;
import net.fabricmc.fabric.api.attachment.v1.AttachmentType;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.Identifier;
// A number saved on each player (Fabric API attachments). Every join adds 1 and the player is told.
public final class JoinMemoryAttach {
public static final AttachmentType<Integer> JOINS = AttachmentRegistry.createPersistent(
Identifier.fromNamespaceAndPath("examplemod", "join_memory"), Codec.INT);
private JoinMemoryAttach() {
}
// Called from the mod's onInitialize.
public static void register() {
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
int joins = handler.getPlayer().getAttachedOrElse(JOINS, 0) + 1;
handler.getPlayer().setAttached(JOINS, joins);
handler.getPlayer().sendSystemMessage(Component.literal("Your joins: " + joins));
});
}
}

In your main mod class, inside onInitialize:

JoinMemoryAttach.register();

Uses:

  • CapabilityManager.get
  • ICapabilitySerializable
  • AttachCapabilitiesEvent
  • RegisterCapabilitiesEvent
  • PlayerEvent.Clone

Forge 1.20.1 has no data attachments: per-player data is a capability, attached in AttachCapabilitiesEvent. For one small value, Player#getPersistentData() (an NBT tag that is saved with the player) is a shorter option.

src/main/java/com/example/examplemod/registry/JoinMemoryAttach.java

package com.example.examplemod.registry;
import net.minecraft.Util;
import net.minecraft.network.chat.TextComponent;
import com.example.examplemod.ExampleMod;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityToken;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.IEventBus;
// A number saved on each player (a Forge capability). Every join adds 1 and the player is told.
public final class JoinMemoryAttach {
public static final Capability<Joins> JOINS = CapabilityManager.get(new CapabilityToken<>() {
});
private static final ResourceLocation ID = new ResourceLocation(ExampleMod.MOD_ID, "join_memory");
private JoinMemoryAttach() {
}
// The data itself.
public static class Joins {
private int count;
public int increment() {
return ++count;
}
}
// Holds one Joins per player and saves it with the player.
private static class Provider implements ICapabilitySerializable<CompoundTag> {
private final Joins joins = new Joins();
private final LazyOptional<Joins> holder = LazyOptional.of(() -> joins);
@Override
public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
return cap == JOINS ? holder.cast() : LazyOptional.empty();
}
@Override
public CompoundTag serializeNBT() {
CompoundTag tag = new CompoundTag();
tag.putInt("joins", joins.count);
return tag;
}
@Override
public void deserializeNBT(CompoundTag tag) {
joins.count = tag.getInt("joins");
}
}
// Called from the mod's constructor.
public static void register(IEventBus modBus) {
modBus.addListener(JoinMemoryAttach::onRegisterCapabilities);
MinecraftForge.EVENT_BUS.addGenericListener(Entity.class, JoinMemoryAttach::onAttach);
MinecraftForge.EVENT_BUS.addListener(JoinMemoryAttach::onClone);
MinecraftForge.EVENT_BUS.addListener(JoinMemoryAttach::onLogin);
}
private static void onRegisterCapabilities(RegisterCapabilitiesEvent event) {
event.register(Joins.class);
}
private static void onAttach(AttachCapabilitiesEvent<Entity> event) {
if (event.getObject() instanceof Player) {
event.addCapability(ID, new Provider());
}
}
// Keeps the number when a player dies and respawns.
private static void onClone(PlayerEvent.Clone event) {
if (event.isWasDeath()) {
event.getOriginal().reviveCaps();
event.getOriginal().getCapability(JOINS).ifPresent(old ->
event.getPlayer().getCapability(JOINS).ifPresent(now -> now.count = old.count));
event.getOriginal().invalidateCaps();
}
}
private static void onLogin(PlayerEvent.PlayerLoggedInEvent event) {
if (event.getPlayer() instanceof ServerPlayer player) {
player.getCapability(JOINS).ifPresent(joins ->
player.sendMessage(new TextComponent("Your joins: " + joins.increment()), Util.NIL_UUID));
}
}
}

In your main mod class, inside <init>:

JoinMemoryAttach.register(modEventBus);

Uses:

  • SavedData
  • DimensionDataStorage.computeIfAbsent
  • ServerPlayConnectionEvents.JOIN

src/main/java/com/example/examplemod/registry/JoinMemoryAttach.java

package com.example.examplemod.registry;
import net.minecraft.Util;
import net.minecraft.network.chat.TextComponent;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.saveddata.SavedData;
// A number saved for each player, in the world's saved data (this Fabric API has no attachments yet). Every join adds 1 and the player is told.
public class JoinMemoryAttach extends SavedData {
private final Map<UUID, Integer> joins = new HashMap<>();
public static JoinMemoryAttach load(CompoundTag tag) {
JoinMemoryAttach data = new JoinMemoryAttach();
for (String id : tag.getAllKeys()) {
data.joins.put(UUID.fromString(id), tag.getInt(id));
}
return data;
}
@Override
public CompoundTag save(CompoundTag tag) {
joins.forEach((id, count) -> tag.putInt(id.toString(), count));
return tag;
}
public int addJoin(UUID player) {
setDirty();
return joins.merge(player, 1, Integer::sum);
}
public static JoinMemoryAttach get(MinecraftServer server) {
return server.overworld().getDataStorage().computeIfAbsent(JoinMemoryAttach::load, JoinMemoryAttach::new, "examplemod_join_memory");
}
// Called from the mod's onInitialize.
public static void register() {
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
int count = get(server).addJoin(handler.getPlayer().getUUID());
handler.getPlayer().sendMessage(new TextComponent("Your joins: " + count), Util.NIL_UUID);
});
}
}

In your main mod class, inside onInitialize:

JoinMemoryAttach.register();

Uses:

  • SavedData
  • DimensionDataStorage.computeIfAbsent
  • ServerPlayConnectionEvents.JOIN

src/main/java/com/example/examplemod/registry/JoinMemoryAttach.java

package com.example.examplemod.registry;
import net.minecraft.Util;
import net.minecraft.network.chat.TextComponent;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.saveddata.SavedData;
// A number saved for each player, in the world's saved data (this Fabric API has no attachments yet). Every join adds 1 and the player is told.
public class JoinMemoryAttach extends SavedData {
private static final String ID = "examplemod_join_memory";
private final Map<UUID, Integer> joins = new HashMap<>();
public JoinMemoryAttach() {
super(ID);
}
@Override
public void load(CompoundTag tag) {
for (String id : tag.getAllKeys()) {
joins.put(UUID.fromString(id), tag.getInt(id));
}
}
@Override
public CompoundTag save(CompoundTag tag) {
joins.forEach((id, count) -> tag.putInt(id.toString(), count));
return tag;
}
public int addJoin(UUID player) {
setDirty();
return joins.merge(player, 1, Integer::sum);
}
public static JoinMemoryAttach get(MinecraftServer server) {
return server.overworld().getDataStorage().computeIfAbsent(JoinMemoryAttach::new, ID);
}
// Called from the mod's onInitialize.
public static void register() {
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
int count = get(server).addJoin(handler.player.getUUID());
handler.player.sendMessage(new TextComponent("Your joins: " + count), Util.NIL_UUID);
});
}
}

In your main mod class, inside onInitialize:

JoinMemoryAttach.register();

Uses:

  • CapabilityInject
  • CapabilityManager.register
  • ICapabilitySerializable
  • AttachCapabilitiesEvent
  • PlayerEvent.Clone

Forge 1.16.5 has no data attachments: per-player data is a capability, attached in AttachCapabilitiesEvent. For one small value, PlayerEntity#getPersistentData() (an NBT tag that is saved with the player) is a shorter option.

src/main/java/com/example/examplemod/registry/JoinMemoryAttach.java

package com.example.examplemod.registry;
import com.example.examplemod.ExampleMod;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.INBT;
import net.minecraft.util.Direction;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Util;
import net.minecraft.util.text.StringTextComponent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
// A number saved on each player (a Forge capability). Every join adds 1 and the player is told.
public final class JoinMemoryAttach {
// Forge fills this in when the capability is registered.
@CapabilityInject(Joins.class)
public static Capability<Joins> JOINS = null;
private static final ResourceLocation ID = new ResourceLocation(ExampleMod.MOD_ID, "join_memory");
private JoinMemoryAttach() {
}
// The data itself.
public static class Joins {
private int count;
public int increment() {
return ++count;
}
}
// How a Joins is written to and read from NBT (only used by Forge's own helpers; Provider does the saving here).
private static class Storage implements Capability.IStorage<Joins> {
@Override
public INBT writeNBT(Capability<Joins> capability, Joins instance, Direction side) {
CompoundNBT tag = new CompoundNBT();
tag.putInt("joins", instance.count);
return tag;
}
@Override
public void readNBT(Capability<Joins> capability, Joins instance, Direction side, INBT nbt) {
instance.count = ((CompoundNBT) nbt).getInt("joins");
}
}
// Holds one Joins per player and saves it with the player.
private static class Provider implements ICapabilitySerializable<CompoundNBT> {
private final Joins joins = new Joins();
private final LazyOptional<Joins> holder = LazyOptional.of(() -> joins);
@Override
public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
return cap == JOINS ? holder.cast() : LazyOptional.empty();
}
@Override
public CompoundNBT serializeNBT() {
CompoundNBT tag = new CompoundNBT();
tag.putInt("joins", joins.count);
return tag;
}
@Override
public void deserializeNBT(CompoundNBT tag) {
joins.count = tag.getInt("joins");
}
}
// Called from the mod's constructor.
public static void register(IEventBus modBus) {
modBus.addListener(JoinMemoryAttach::onCommonSetup);
MinecraftForge.EVENT_BUS.addGenericListener(Entity.class, JoinMemoryAttach::onAttach);
MinecraftForge.EVENT_BUS.addListener(JoinMemoryAttach::onClone);
MinecraftForge.EVENT_BUS.addListener(JoinMemoryAttach::onLogin);
}
private static void onCommonSetup(FMLCommonSetupEvent event) {
CapabilityManager.INSTANCE.register(Joins.class, new Storage(), Joins::new);
}
private static void onAttach(AttachCapabilitiesEvent<Entity> event) {
if (event.getObject() instanceof PlayerEntity) {
event.addCapability(ID, new Provider());
}
}
// Keeps the number when a player dies and respawns (Forge 1.16.5 revives the old player's capabilities for this event).
private static void onClone(PlayerEvent.Clone event) {
if (event.isWasDeath()) {
event.getOriginal().getCapability(JOINS).ifPresent(old ->
event.getPlayer().getCapability(JOINS).ifPresent(now -> now.count = old.count));
}
}
private static void onLogin(PlayerEvent.PlayerLoggedInEvent event) {
if (event.getPlayer() instanceof ServerPlayerEntity) {
ServerPlayerEntity player = (ServerPlayerEntity) event.getPlayer();
player.getCapability(JOINS).ifPresent(joins ->
player.sendMessage(new StringTextComponent("Your joins: " + joins.increment()), Util.NIL_UUID));
}
}
}

In your main mod class, inside <init>:

JoinMemoryAttach.register(modEventBus);

Uses:

  • CapabilityInject
  • CapabilityManager.register
  • ICapabilitySerializable
  • AttachCapabilitiesEvent
  • PlayerEvent.Clone

Forge 1.12.2 has no data attachments: per-player data is a capability, attached in AttachCapabilitiesEvent. For one small value, the player’s own getEntityData() tag is a shorter option.

src/main/java/com/example/examplemod/registry/JoinMemoryAttach.java

package com.example.examplemod.registry;
import com.example.examplemod.ExampleMod;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent;
// A number saved on each player (a Forge capability). Every join adds 1 and the player is told.
@Mod.EventBusSubscriber(modid = ExampleMod.MOD_ID)
public final class JoinMemoryAttach {
// Forge fills this in when the capability is registered.
@CapabilityInject(Joins.class)
public static Capability<Joins> JOINS = null;
private static final ResourceLocation ID = new ResourceLocation(ExampleMod.MOD_ID, "join_memory");
private JoinMemoryAttach() {
}
// The data itself.
public static class Joins {
private int count;
public int increment() {
return ++count;
}
}
// How a Joins is written to and read from NBT.
private static class Storage implements Capability.IStorage<Joins> {
@Override
public NBTBase writeNBT(Capability<Joins> capability, Joins instance, EnumFacing side) {
NBTTagCompound tag = new NBTTagCompound();
tag.setInteger("joins", instance.count);
return tag;
}
@Override
public void readNBT(Capability<Joins> capability, Joins instance, EnumFacing side, NBTBase nbt) {
instance.count = ((NBTTagCompound) nbt).getInteger("joins");
}
}
// Holds one Joins per player and saves it with the player.
private static class Provider implements ICapabilitySerializable<NBTTagCompound> {
private final Joins joins = new Joins();
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
return capability == JOINS;
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
return capability == JOINS ? JOINS.cast(joins) : null;
}
@Override
public NBTTagCompound serializeNBT() {
return (NBTTagCompound) JOINS.getStorage().writeNBT(JOINS, joins, null);
}
@Override
public void deserializeNBT(NBTTagCompound tag) {
JOINS.getStorage().readNBT(JOINS, joins, null, tag);
}
}
// Called from preInit.
public static void register() {
CapabilityManager.INSTANCE.register(Joins.class, new Storage(), Joins::new);
}
@SubscribeEvent
public static void onAttach(AttachCapabilitiesEvent<Entity> event) {
if (event.getObject() instanceof EntityPlayer) {
event.addCapability(ID, new Provider());
}
}
// Keeps the number when a player dies and respawns.
@SubscribeEvent
public static void onClone(PlayerEvent.Clone event) {
if (event.isWasDeath() && event.getOriginal().hasCapability(JOINS, null)) {
event.getEntityPlayer().getCapability(JOINS, null).count = event.getOriginal().getCapability(JOINS, null).count;
}
}
@SubscribeEvent
public static void onLogin(PlayerLoggedInEvent event) {
Joins joins = event.player.getCapability(JOINS, null);
if (joins != null) {
event.player.sendMessage(new TextComponentString("Your joins: " + joins.increment()));
}
}
}

In your main mod class, inside preInit:

JoinMemoryAttach.register();

Linen’s How-tos library has this page too, with the example for your own mod’s loader and Minecraft version. Hover a name in your code and Linen points to the how-tos that explain it. Both are free. Download Linen.