Skip to content

Instantly share code, notes, and snippets.

@jasonw4331
Last active August 3, 2018 21:31
Show Gist options
  • Save jasonw4331/55351cf1a1d1356bc928a1ddd275407e to your computer and use it in GitHub Desktop.
Save jasonw4331/55351cf1a1d1356bc928a1ddd275407e to your computer and use it in GitHub Desktop.
<?php
#Adding NBT tag "test" (string), which has a value of "hey"
/** @var Item $item */
$nbt = $item->getNamedTag() ?? new CompoundTag("", []);
$nbt->test = new StringTag("test", "hey");
$item->setNamedTag($nbt);
#If item has NBT tag "test", do something
/** @var Item $item */
if (isset($item->getNamedTag()->test)) {
//$item has NBT tag: test.
/** @var string $test */
$test = $item->getNamedTag()->test;
}
#Unsetting/Removing NBT tag "test"
/** @var Item $item */
$nbt = $item->getNamedTag() ?? new CompoundTag("", []);
unset($nbt->test);
$item->setNamedTag($nbt);
#Adding NBT tag "test" (integer)
/** @var Item $item */
$nbt = $item->getNamedTag() ?? new CompoundTag("", []);
$nbt->test = new IntTag("test", 69);
$item->setNamedTag($nbt);
#If item has NBT tag "test", do something
/** @var Item $item */
if (isset($item->getNamedTag()->test)) {
//$item has NBT tag: test.
/** @var int $test */
$test = $item->getNamedTag()->test->getValue();
}
#Unsetting/Removing NBT tag "test"
/** @var Item $item */
$nbt = $item->getNamedTag() ?? new CompoundTag("", []);
unset($nbt->test);
$item->setNamedTag($nbt);
#If the $item was in a (Player)$player's hand, you must update it after interfering with the NBT tag by...
$player->getInventory()->setItemInHand($item);
#For saving an array of integers to NBT, use IntArrayTag
/** @var Item $item */
$nbt = $item->getNamedTag() ?? new CompoundTag("", []);
$nbt->testarray = new IntArrayTag("testarray", [0, 8, 3, 1]);
$item->setNamedTag($nbt);
/** Checking if item has "testarray" tag. */
$nbt = $item->getNamedTag() ?? new CompoundTag("", []);
if (isset($nbt->testarray)) {
//echo $nbt->testarray->getValue();
}
#You can also customize entity's and tile's NBT
/** @var Tile $tile */
$tile->namedtag->test = new StringTag("test", "hey");
/** @var Entity $entity */
$entity->namedtag->test = new StringTag("test", "hey");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment