Skip to content

Instantly share code, notes, and snippets.

@KingAlterIV
Last active February 9, 2024 17:17
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save KingAlterIV/168eb0670151476c144b2cd70373e71e to your computer and use it in GitHub Desktop.
Save KingAlterIV/168eb0670151476c144b2cd70373e71e to your computer and use it in GitHub Desktop.
The proper way of adding a prefix and suffix to nametags of a player using Scoreboard Teams made with packets and is possibly horribly made by me!

Feel free to update and expand upon this.

Requirements

  • ProtocolLib

Code

package your.package.here;

import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.WrappedChatComponent;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Collections;
import java.util.UUID;

public class Nametag {

    PacketContainer packet;

    public Nametag(Player player) {
        this.packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.SCOREBOARD_TEAM);
        String name = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
        this.packet.getIntegers().write(1, 0);
        this.packet.getStrings().write(0, name);
        this.packet.getChatComponents().write(0, WrappedChatComponent.fromText(player.toString()));
        this.packet.getSpecificModifier(Collection.class).write(0, Collections.singletonList(player.getName()));
    }

    public Nametag setPrefix(String prefix) {
        this.packet.getChatComponents().write(1, WrappedChatComponent.fromText(ChatColor.translateAlternateColorCodes('&', prefix) + " "));
        return this;
    }

    public Nametag setSuffix(String suffix) {
        this.packet.getChatComponents().write(2, WrappedChatComponent.fromText(" " + ChatColor.translateAlternateColorCodes('&', suffix)));
        return this;
    }

    public void build() {
        for (Player p : Bukkit.getOnlinePlayers()) {
            try {
                ProtocolLibrary.getProtocolManager().sendServerPacket(p, packet);
            } catch (InvocationTargetException e) {
                throw new RuntimeException("Cannot send packet " + packet, e);
            }
        }
    }
}

Usage

new Nametag(player).setPrefix("&6Test").setSuffix("&aTest").build();

// 1.13+
new Nametag(player).setPrefix("&6Testttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt").setSuffix("&aTestttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt").build();

Image

Image

1.13+ Image2

@Swiftlicious
Copy link

Swiftlicious commented Jun 25, 2020

is there a way to organize the priority of the ranks? i assume I would have to set the name to "0-name" to get that type of effect.

@KingAlterIV
Copy link
Author

There is, but you'll have to use actual teams for that since this is fake teams and I don't think you can prioritize the fake teams cause well, they're fake.

@jonawoning
Copy link

org.bukkit.command.CommandException: Unhandled exception executing command 'k' in plugin Kingdom v1.3-SNAPSHOT
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[server.jar:git-Spigot-642f6d2-57ab4cf]
at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141) ~[server.jar:git-Spigot-642f6d2-57ab4cf]
at org.bukkit.craftbukkit.v1_12_R1.CraftServer.dispatchCommand(CraftServer.java:648) ~[server.jar:git-Spigot-642f6d2-57ab4cf]
at net.minecraft.server.v1_12_R1.PlayerConnection.handleCommand(PlayerConnection.java:1397) [server.jar:git-Spigot-642f6d2-57ab4cf]
at net.minecraft.server.v1_12_R1.PlayerConnection.a(PlayerConnection.java:1232) [server.jar:git-Spigot-642f6d2-57ab4cf]
at net.minecraft.server.v1_12_R1.PacketPlayInChat.a(PacketPlayInChat.java:45) [server.jar:git-Spigot-642f6d2-57ab4cf]
at net.minecraft.server.v1_12_R1.PacketPlayInChat.a(PacketPlayInChat.java:1) [server.jar:git-Spigot-642f6d2-57ab4cf]
at net.minecraft.server.v1_12_R1.PlayerConnectionUtils$1.run(SourceFile:13) [server.jar:git-Spigot-642f6d2-57ab4cf]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) [?:?]
at java.util.concurrent.FutureTask.run(FutureTask.java:264) [?:?]
at net.minecraft.server.v1_12_R1.SystemUtils.a(SourceFile:46) [server.jar:git-Spigot-642f6d2-57ab4cf]
at net.minecraft.server.v1_12_R1.MinecraftServer.D(MinecraftServer.java:748) [server.jar:git-Spigot-642f6d2-57ab4cf]
at net.minecraft.server.v1_12_R1.DedicatedServer.D(DedicatedServer.java:406) [server.jar:git-Spigot-642f6d2-57ab4cf]
at net.minecraft.server.v1_12_R1.MinecraftServer.C(MinecraftServer.java:679) [server.jar:git-Spigot-642f6d2-57ab4cf]
at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:577) [server.jar:git-Spigot-642f6d2-57ab4cf]
at java.lang.Thread.run(Thread.java:832) [?:?]
Caused by: com.comphenix.protocol.reflect.FieldAccessException: No field with type net.minecraft.server.v1_12_R1.IChatBaseComponent exists in class PacketPlayOutScoreboardTeam.
at com.comphenix.protocol.reflect.StructureModifier.writeInternal(StructureModifier.java:348) ~[?:?]
at com.comphenix.protocol.reflect.StructureModifier.write(StructureModifier.java:328) ~[?:?]
at nl.snowpix.kingdom.Tab.NameTag.(NameTag.java:24) ~[?:?]
at nl.snowpix.kingdom.commands.KingdomCommand.onCommand(KingdomCommand.java:784) ~[?:?]
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[server.jar:git-Spigot-642f6d2-57ab4cf]
... 15 more

This error!

@arthurr0
Copy link

arthurr0 commented May 5, 2022

Hi, can you help?

com.comphenix.protocol.reflect.FieldAccessException: Field index out of bounds. (Index: 1, Size: 1)
        at com.comphenix.protocol.reflect.StructureModifier.writeInternal(StructureModifier.java:373) ~[ProtocolLib.jar:?]
        at com.comphenix.protocol.reflect.StructureModifier.write(StructureModifier.java:349) ~[ProtocolLib.jar:?]
        at com.mcmanhunt.shared.helper.NametagHelper.<init>(NametagHelper.java:24) ~[mcmanhunt-network-game.jar:?]
        at com.mcmanhunt.game.manhunt.listener.game.StartGameListener.lambda$onStart$0(StartGameListener.java:106) ~[mcmanhunt-network-game.jar:?]
        at java.lang.Iterable.forEach(Iterable.java:75) ~[?:?]
        at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1092) ~[?:?]
        at com.mcmanhunt.game.manhunt.listener.game.StartGameListener.onStart(StartGameListener.java:60) ~[mcmanhunt-network-game.jar:?]
        at com.destroystokyo.paper.event.executor.asm.generated.GeneratedEventExecutor72.execute(Unknown Source) ~[?:?]
        at org.bukkit.plugin.EventExecutor.lambda$create$1(EventExecutor.java:75) ~[paper-api-1.18.2-R0.1-SNAPSHOT.jar:?]
        at co.aikar.timings.TimedEventExecutor.execute(TimedEventExecutor.java:80) ~[paper-api-1.18.2-R0.1-SNAPSHOT.jar:git-Paper-313]
        at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.java:70) ~[paper-api-1.18.2-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.java:669) ~[paper-api-1.18.2-R0.1-SNAPSHOT.jar:?]
        at com.mcmanhunt.game.manhunt.runnable.GameWorkTask.run(GameWorkTask.java:103) ~[mcmanhunt-network-game.jar:?]
        at org.bukkit.craftbukkit.v1_18_R2.scheduler.CraftTask.run(CraftTask.java:101) ~[paper-1.18.2.jar:git-Paper-313]
        at org.bukkit.craftbukkit.v1_18_R2.scheduler.CraftScheduler.mainThreadHeartbeat(CraftScheduler.java:483) ~[paper-1.18.2.jar:git-Paper-313]
        at net.minecraft.server.MinecraftServer.tickChildren(MinecraftServer.java:1531) ~[paper-1.18.2.jar:git-Paper-313]
        at net.minecraft.server.dedicated.DedicatedServer.tickChildren(DedicatedServer.java:483) ~[paper-1.18.2.jar:git-Paper-313]
        at net.minecraft.server.MinecraftServer.tickServer(MinecraftServer.java:1455) ~[paper-1.18.2.jar:git-Paper-313]
        at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:1225) ~[paper-1.18.2.jar:git-Paper-313]
        at net.minecraft.server.MinecraftServer.lambda$spin$0(MinecraftServer.java:315) ~[paper-1.18.2.jar:git-Paper-313]
        at java.lang.Thread.run(Thread.java:833) ~[?:?]
        ```

@Zorioux
Copy link

Zorioux commented Jun 12, 2022

this is very helpful, thank you for it, I have 1 issue the name is permanently colored black, I add colors to prefix and suffix and it works, but I can't figure out how to change the player name color, can you help with this?

@PedroMPagani
Copy link

PedroMPagani commented Sep 19, 2022

is there a way to organize the priority of the ranks? i assume I would have to set the name to "0-name" to get that type of effect.

You can, just for sake of mind.

Team priorities work under the beggining identifiers:
00
01
02
03
11
15
20

00 shows up first, consider the priorities as if they were indexes in the tablist!

This gist is only lacking how to properly handle the team for the client too, so it removes the team later if player leaves etc

@heytek
Copy link

heytek commented Dec 29, 2022

this is very helpful, thank you for it, I have 1 issue the name is permanently colored black, I add colors to prefix and suffix and it works, but I can't figure out how to change the player name color, can you help with this?

I also have this problem

@imDMK
Copy link

imDMK commented Mar 16, 2023

Not work on 1.19.2.
Will you improve the code to work with the latest versions?
Thanks!

@Ayouuuu
Copy link

Ayouuuu commented Aug 4, 2023

this is very helpful, thank you for it, I have 1 issue the name is permanently colored black, I add colors to prefix and suffix and it works, but I can't figure out how to change the player name color, can you help with this?

minecraft 1.18.2

InternalStructure structure = this.packet.getOptionalStructures().readSafely(0).get();
structure.getEnumModifier(ChatColor.class, MinecraftReflection.getMinecraftClass("EnumChatFormat")).write(0, color);

@Ayouuuu
Copy link

Ayouuuu commented Aug 4, 2023

1.18.2 and higher code

/**
 * Minecraft version 1.18.2
 */
public class Nametag {

    PacketContainer packet;
    private final InternalStructure structure;
    private final Player player;

    public Nametag(Player player) {
        this.player = player;
        this.packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.SCOREBOARD_TEAM);
        String name = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
        this.packet.getIntegers().write(0, 0);
        this.packet.getStrings().write(0, name);
        this.packet.getSpecificModifier(Collection.class).write(0, Collections.singletonList(player.getName()));
        this.structure = this.packet.getOptionalStructures().readSafely(0).get();
    }

    public Nametag setPrefix(String prefix) {
        this.structure.getChatComponents().write(1, WrappedChatComponent.fromText(ChatColor.translateAlternateColorCodes('&', prefix)));
        return this;
    }

    public Nametag color(ChatColor color) {
        this.structure.getEnumModifier(ChatColor.class, MinecraftReflection.getMinecraftClass("EnumChatFormat"))
                .write(0, color);
        return this;
    }

    public Nametag setSuffix(String suffix) {
        this.structure.getChatComponents().write(2, WrappedChatComponent.fromText(ChatColor.translateAlternateColorCodes('&', suffix)));
        return this;
    }

    public void build(Collection<? extends Player> players) {
        if (players.isEmpty()) return;
        this.structure.getIntegers().write(0, 3);
        this.packet.getOptionalStructures().write(0, Optional.of(structure));
        for (Player p : players) {
            try {
                ProtocolLibrary.getProtocolManager().sendServerPacket(p, packet);
            } catch (Exception e) {
                throw new RuntimeException("Cannot send packet " + packet, e);
            }
        }
    }

    public void build() {
        this.build(Bukkit.getOnlinePlayers());
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment