Solved Can't pickup some items .dropItems()

Discussion in 'Spigot Plugin Development' started by KingStared, Dec 2, 2019 at 11:46 PM.

  1. When it drops items sometimes I can't pick up the items. I have tried deleting everything in the server and redoing it but still, it doesn't work.

    Example:
    https://imgur.com/rp8Ml9n


    Code (Java):
                if (breakBlockList.contains(dummyItem)) {

                    Location blockLoc = e.getBlock().getLocation();
                    blockLoc.setX(blockLoc.getX() + 0.5);
                    blockLoc.setZ(blockLoc.getZ() + 0.5);

                    Random rand = new Random();
                    ItemStack randomItem = materialList.get(rand.nextInt(materialList.size()));

                    if (randomItem.getMaxStackSize() > 1) {
                        randomItem.setAmount(rand.nextInt(16));
                    }else {
                        randomItem.setAmount(1);
                    }

                    System.out.println(randomItem);
                    if (randomItem.getType().equals(Material.ENCHANTED_BOOK)) {
                        EnchantmentStorageMeta enchantMeta = (EnchantmentStorageMeta) randomItem.getItemMeta();
                        Enchantment randEnchant = enchants.get(rand.nextInt(enchants.size()));

                        enchantMeta.addStoredEnchant(randEnchant, 1, true);
                        randomItem.setItemMeta(enchantMeta);

                    }
                    e.getBlock().setType(Material.AIR);
                    e.setCancelled(true);
               
                    Bukkit.getWorld("uhc").dropItem(blockLoc, randomItem);


                }
     
  2. Calling Random::nextInt means the initial argument is inclusive and the last is exclusive. In other words, your current code will only generate numbers from 0-15, for an ItemStack amount. Whenever 0 is produced, it may be causing your issue. Adjust your range so that it's between 0 and 16.

    Either switch to using the random provided by ThreadLocalRandom: ThreadLocalRandom.current().nextInt(1, 17);
    or adjust the range in your current random: rand.nextInt(16) + 1;
     
    • Agree Agree x 3
  3. Wow you're a lifesaver. It's working now. I totally just looked over this thanks.