Ezrab_
Ezrab_

Reputation: 983

Bukkit toggling a scoreboard

I would like to toggle a scoreboard in bukkit by using a command '/sb toggle'. However I can't seem to make it work because the compiler keeps looping through the code. So if I remove a key from the ArrayList, the compiler will continue it's executing which isn't what I want.

// Creating the ArrayList to store the data.

ArrayList<UUID> toggle = new ArrayList<>();

// Checking if it contains the player's UUID.

    if (toggle.contains(p.getUniqueId())) {

// Removing the UUID from the ArrayList to turn the scoreboard off.
        toggle.remove(p.getUniqueId());
        p.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
        p.sendMessage(Main.msg + ChatColor.RED + "Scoreboard turned off.");
    } else {
// Adding the UUID again to the ArrayList so that we it can turn on.
        toggle.add(p.getUniqueId());
        SideScoreboard.getInstance().setScoreboardPlayer(p);
        p.sendMessage(ChatColor.GREEN + "Scoreboard turned on.");
    }

So the problem is that it keeps telling me that the Scoreboard is turned on. When it really should just toggle between off and on each time I execute the command.

Upvotes: 0

Views: 200

Answers (1)

Kirill
Kirill

Reputation: 449

When this method is called, every line within it will run, one by one.

Look at your first line,

ArrayList<UUID> toggle = new ArrayList<>();

Every time the method runs, a new, empty ArrayList is created and assigned to toggle. More so than the scope of the variable, this is the root of the problem.

Once the if statement is reached,

if (toggle.contains(p.getUniqueId()))

toggle will still refer to the empty ArrayList that was just assigned to it. It does not contain anything, so it certainly won't contain p.getUniqueId().

The fix here is to give toggle a broader scope than the method, and not reassign it each time this method runs. This might look like this:

public class MyClass{
    private ArrayList<UUID> toggle = new ArrayList<>();

    public void toggleScoreboard(Player p){
        if (toggle.contains(p.getUniqueId()))
        // Rest of your code here
    }
}

Then every time the method runs, it refer to the same ArrayList, which will persist the values stored in it.

Upvotes: 1

Related Questions