Accessing variable from outside runnable within the runnable

Discussion in 'Plugin Development' started by Jncwhite01, Apr 15, 2018.

Thread Status:
Not open for further replies.
  1. Offline

    Jncwhite01

    Hellllooooo, im currently creating a Crates plugin, just to test my ability as I recently started delving into Java further and the Bukkit/Spigot API.

    I currently have (almost) everything else working, however trying to add the item which is currently being displayed in the middle of the crate GUI to the player inventory and cant change my variable due to variable scope. Setting the variable to final wont work as I need to update the variable with the new value. I even tried creating an ArrayList for one item and added it to it, but that didnt work either (I know this would of not the been the best way to do it)

    Anway, any help is greatly appreiciated, heres my current code:

    Code:
    ItemStack toGive = null;
           
            for(int i = 0; i < 20; i++)
            {
                final Sound sound = Sound.ENTITY_EXPERIENCE_ORB_PICKUP;
               
                new BukkitRunnable() {
                    public void run() {
                       
                        for(int i = 0; i < inv.getSize(); i++)
                        {
                            ItemStack glass = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) random.nextInt(11));
                            inv.setItem(i, glass);
                        }
                       
                        ItemStack item = new ItemStack(prizes.get(random.nextInt(prizes.size())));
                        inv.setItem(13, item);
                       
                        p.playSound(p.getLocation(), sound, 1, 1);
                    }
                }.runTaskLater(this, i*3);
            }
           
            p.getInventory().addItem(toGive);
        }
     
  2. @Jncwhite01
    If you're trying to give the player this item

    ItemStack item = new ItemStack(prizes.get(random.nextInt(prizes.size())));
    then don't create a new itemstack just set toGive to it

    toGive = new ItemStack(prizes.get(random.nextInt(prizes.size())));
     
    MightyOne likes this.
Thread Status:
Not open for further replies.

Share This Page