Home

Minecraft Modding: Storing custom NBT data

So for a secret idea for a mod, I was learning how to store data on a player. The best way to do this that I know of would be to use NBT data, which is saved on the world per player. NBT data can include many things about the player, like health, potion effects, hunger, strength, etc. It is more commonly used in entities, for things like velocity, age, speed (for horses). You can often see this when you use the /summon command for mobs with custom data.

I was having lots of trouble, starting with getting the NBT data of a player upon joining a worldserver (single or multiplayer). If the player didn't have my custom data stored on him/her, it would create the data with a default value. This is almost only used when a new player joins the worldserver. However, the function that I was using (player.getNBTTagCompound()) was giving me a bit of trouble. Every time I tried using the hasKey() function (to test whether the player has a certain bit of data), it crashed. I led this down to the fact that the getNBTTagCompound function was actually returning null. To see why, I looked at the vanilla function for this.

Guess what? The function had a single line of code. "return null;". WHAT?!? Why on EARTH would you have a function return null, unless you purposely wanted it to crash the game. It might have been there because the Mojangsta working on updating that found too many dependencies on that function and lazily didn't fix the errors by updating the code; he simply made the function return null. And, as it turns out, that didn't cause any problems. Until now, when it was extremely misleading.

Anyway, I found a function called readFromNBT() which accepted an NBT tag. I assumed from how other people used this function that it would basically input the NBT tag I put into the function with all the data values of the player. This would mean creating an empty NBT variable, then using readFromNBT to input it with data.

As it turned out, I was half right. There was another function, writeToNBT() (again, taking an NBT tag variable) which I assumed would apply the NBT tag to the player. Like I said before, I was half right. Every time I joined the world, it set me to 0,0,0 coordinate position. It really confused me. Then, suddenly, I facepalmed. Of course, duh. I got the functions mixed up. The writeToNBT() function would write the player's data to a variable, while readFromNBT() would take the data of the variable and write it to the player.

I haven't yet gotten a chance to try it out, but I'm looking forward to it tomorrow.