Scoreboards error?

Hello Sponge contributors,
So I have tried to create a test sponge scoreboard with this code, but it didnt work(Do i have to register it? And if yes where?)

@Listener
public void onEntity(ClientConnectionEvent.Join e) {
Player p = e.getTargetEntity();

    Scoreboard sb = Scoreboard.builder().build();
    Objective obj = Objective.builder().criterion(Criteria.DUMMY).displayName(Text.of("MSB")).name("MainSideBoard").build();
    java.util.Optional<Score> s = obj.getScore(Text.of("Online:"));
    if(s.isPresent()){
        Score s1 = s.get();
        s1.setScore(1);
    }
    sb.addObjective(obj);
    sb.updateDisplaySlot(obj, DisplaySlots.SIDEBAR);
    p.setScoreboard(sb);
}

This gives me no ERRORS, but without the Optional it would give me a "java.util.NoSuchElementException: No value present" . Did I do something wrong?
The scoreboard does not show up, it only gives an error without the Optinal, but the optinal just filters the NoSuch… thing out. Any ideas?(an example code would also be helpful)

Remove the optional and replace obj.getScore(Text.of("Online:")); with obj.getOrCreateScore(Text.of("Online:"));

You have created a new Objective. That means there is no Score with the name “Text.of("Online:")” in it yet and the getScore() method returns an empty Optional.
With getOrCreateScore() the Objective is tested if there is any Score with that name and if not, creates a new Score, adds it to the Objective and returns it. :slight_smile:

Example code:

@Listener
public void onEntity(ClientConnectionEvent.Join e) {
    Player p = e.getTargetEntity();
    Scoreboard sb = Scoreboard.builder().build();

    Objective obj = Objective.builder().criterion(Criteria.DUMMY).displayName(Text.of("MSB")).name("MainSideBoard").build();
    Score s = obj.getOrCreateScore(Text.of("Online:"));
    s.setScore(1);

    sb.addObjective(obj);
    sb.updateDisplaySlot(obj, DisplaySlots.SIDEBAR);
    p.setScoreboard(sb);
}
2 Likes

Works Thank you