In case any other people are going to look at this in the future.
Final WorldSavedData object:
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraft.world.storage.MapStorage;
import net.minecraft.world.storage.WorldSavedData;
public class DataTest extends WorldSavedData {
private static final String DATA_NAME = "ModID_Test";
private static DataTest instance;
private int testInt;
public DataTest() {
super(DATA_NAME);
}
public DataTest(String name) {
super(name);
}
public static DataTest get(World world) {
MapStorage storage = world.getMapStorage();
instance = (DataTest) storage.getOrLoadData(DataTest.class, DATA_NAME);
if (instance == null) {
instance = new DataTest();
storage.setData(DATA_NAME, instance);
}
return instance;
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
testInt = nbt.getInteger("testInt");
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
compound.setInteger("testInt", testInt);
return compound;
}
public void setCharData(int testInt) {
this.testInt = testInt;
markDirty();
}
public int getTestInt() {
return testInt;
}
}
Using the WorldSavedData object from a PlayerEvent type: (Only example, you can get it from other ways, just keep in mind we have to use the Logical Server Side world)
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
@Mod.EventBusSubscriber(modid = Reference.MOD_ID)
public class ServerListener {
@SubscribeEvent(priority = EventPriority.NORMAL)
public static void playerConnected(PlayerEvent.PlayerLoggedInEvent event) {
DataTest data = DataTest.get(event.player.world);
if(data != null) {
int testInt = data.getCharData();
System.out.println("Value: "+testInt);
}
}
@SubscribeEvent(priority = EventPriority.NORMAL)
public static void playerDisconnected(PlayerEvent.PlayerLoggedOutEvent event) {
DataTest data = DataTest.get(event.player.world);
if(data != null) {
data.setCharData(1);
System.out.println("Value: "+testInt);
}
}
}