Are there commands to get the display name of the local player. So if I create a chat message, all players seen their own name in the chat. Is it possible and how?
No, you can't get the "local" player name, because who will run the code is the server, not the client, so you can't get it because there is no local player. However, you can still send a custom message for different people with different names to simulate this effect.
Based in this example, you can simply send a message through the /tellraw command to the players that you want to send the message, example:
public static void sendMessage(String playerName, String msg) {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(),
"/tellraw " + playerName + " {\"text\":\"" + msg.replaceAll("<playername>", playerName) + "\"}");
}
In this case, I've used <playername>
as a keyword to reference the player, so Hello <playername>
should return Hello yourname
...
However, this solution is better when you don't have the Player object, and to not waste your machine's time to create it, you can simply use the tellraw... But to simplify the answer, you can use the Player::sendMessage
method (quoted by bcsb1001).:
public static void sendMessage(Player player, String msg){
player.sendMessage(msg.replaceAll("<playername>", player.getName()));
}
Okay, but how can I send it to every person in a group, or in an Array?
In this case, you can use a for each
loop for every single player.
Here is the full code to send a hello message to every single player online:
public static void sayHelloToEveryone() {
String msg = "Hello <playername>!";
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
p.sendMessage(msg.replaceAll("<playername>", p.getName()));
}
}
Therefore, when you use sayHelloToEveryone()
, it will send a message to everyone based on their name:
If there are Steve and Ruben online, the server will send a different message to both users:
Steve's chat: Hello Steve!
Ruben's chat: Hello Ruben!