Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package de.syscy.adventureplugin.listener;
import de.syscy.adventureplugin.AdventurePlugin;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.metadata.FixedMetadataValue;
import java.util.UUID;
public class ItemDropListener implements Listener {
private static AdventurePlugin plugin;
private @Getter @Setter boolean autoProtectDroppedItems = true;
public ItemDropListener(AdventurePlugin plugin) {
ItemDropListener.plugin = plugin;
}
public static void protectDroppedItem(Item item, Player owner) {
protectDroppedItem(item, owner.getUniqueId());
}
public static void protectDroppedItem(Item item, UUID ownerId) {
item.setMetadata("ownerUUID", new FixedMetadataValue(plugin, ownerId));
}
public static void markRemoveOnPickup(Item item) {
item.setMetadata("removeOnPickup", new FixedMetadataValue(plugin, true));
}
@EventHandler
public void onDropItem(PlayerDropItemEvent event) {
if(autoProtectDroppedItems) {
event.getItemDrop().setMetadata("ownerUUID", new FixedMetadataValue(plugin, event.getPlayer().getUniqueId()));
}
}
@EventHandler
public void onPickupItem(EntityPickupItemEvent event) {
if(event.getItem().hasMetadata("ownerUUID")) {
if(event.getEntityType() == EntityType.PLAYER) {
Player player = (Player) event.getEntity();
UUID ownerUUID = (UUID) event.getItem().getMetadata("ownerUUID").get(0).value();
event.setCancelled(!player.getUniqueId().equals(ownerUUID));
} else {
event.setCancelled(autoProtectDroppedItems);
}
}
if(event.getItem().hasMetadata("removeOnPickup") && !event.isCancelled()) {
event.setCancelled(true);
event.getItem().remove();
}
}
}
@Kage0x3B
Copy link
Author

Kage0x3B commented Jun 15, 2018

Example code for the Spigot thread https://www.spigotmc.org/threads/creating-infinity-unpickable-item.323988 because it has a pretty similar problem.

To solve the exact problem in the Spigot thread, the protectDroppedItem method would have to be changed to just set a boolean metadata key to mark the item as not pickupable. The onPickupItem method also just needs to check for the presence of the metadata key then and cancel the event if the metadata is present.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment