Finding out who is the owner of an inventory

Is there any way to find who is the owner of an inventory?
I’m trying to prevent the player from interacting with its own inventory only.
I tried doing this:

public void onInventoryInteract(InteractInventoryEvent event) {
  event.getCause().get(NamedCause.SOURCE, Player.class).ifPresent(player -> {
    if (event.getTargetInventory().equals(player.getInventory())) {

I noticed the inventory is an instance of net.minecraft.inventory.ContainerPlayer, however that’s not a Sponge class so I think I should avoid using it in my code.

You can just check if the player is at the root of the cause.

Wouldn’t that trigger if the player opens any other inventory (e.g. chest) as well?
I want to prevent the player from interacting with its own inventory only, and let him use any other inventory normally.

That’s not currently possible, but will be once Custom Inventories are implemented (the PR adds support for detecting the inventory type).

1 Like

You can check if the inventory is an instance of a CarriedInventory. If it is, then getCarrier() is the owner.

doesn’t work, event.getTargetInventory() instanceof CarriedInventory is false

That could be because the inventory is a sub-inventory. Use inventory.parent() in order to climb up to the top player inventory object.
Once you get a HumanInventory, then it should work as it extends CarriedInventory

inventory.parent() is null, the inventory itself is an instance of net.minecraft.inventory.ContainerPlayer.

You’ll find the vast majority of objects you have are instances of Minecraft classes, this is because the way Sponge is implemented the Minecraft classes implement the Sponge ones at runtime.