Get the slot of an object

Discussion in 'Spigot Plugin Development' started by Dapla365, Jul 13, 2018.

  1. I need help to get the slot of an object that the player has but I do not know how to do it. The player
    is in a world of the config.yml
    NOTE:
    List <String> w = config.getStringList("example");
    String world = jugador.getWorld().getName();
    for(int i=0;i<w.size();i++) {
    if(w.get(i).equals(world)) {
    }
    }
     
  2. Optic_Fusion1

    Resource Staff

    This is not a resource, remove the resource tag
     
    • Agree Agree x 1
  3. sorry, I was wrong
     
  4. Strahan

    Benefactor

    The player's inventory has a getHeldItemSlot() method.
     
  5. 1. Put [-code-] (no -'s) tags around your code. You can do it with [code-] [-/code] (remove the -'s)
    2. How does a player's world have anything to do with getting the slot of an itemstack in a player's inventory.
    3. (See how I used code tags?)
    Code (Java):
    int slot = -1;
    for(int i; i < player.getInventory().size(); i++) { // Go through each inventory slot
        if(player.getInventory().getItem(i).equals(item)) { // Check if the item in the slot is the right item
            slot = i; // If so, set the slot variable to the slot index
            break; // Break the loop because you're done
        }
    }
    if(slot == -1) { // What if the item wasn't found?
        System.out.println("Item is not in player's inventory");
        return; // Tell the console it wasn't found and return so it doesn't go any further
    }
    That's how to get the slot of an item.
     
  6. but, and if I have for example a sword in slot 2 of my inventory as I take the slot where the sword is located?
     
  7. Strahan

    Benefactor

    You can use [PLAIN] tags to be able to advise someone on what tags to use without that dash bullshit :)

    What? If you know the sword is in slot 2, then it's in slot 2. I have no idea what you are asking. If you want to get the slot of the item the player is holding, do it the way I shown you. If you have an item and just want to see what slot it is at in the player's inventory in general, use MCGamer's example. Just bear in mind if you are trying to find, say, if they have a diamond sword in general I wouldn't quite do it the way he displayed because it wouldn't match if the sword was named or has an enchant or something. A base material match would be better then. I'd also do a .contains check first so as not to waste time looping unnecessarily if they do not have it rather than futz with the -1 thing.
     
    • Agree Agree x 1
  8. I'm not 100 percent (not at an IDE) but
    Code (Java):
    Arrays.asList(player.getInventory().getContents()).indexOf(item);
    Edit: I'm not sure what it returns if it's not in the collection.
     
  9. FrostedSnowman

    Resource Staff

    -1 is returned if an element isn't found in lists
     
    • Like Like x 1