Bukkit Coding – (7) Getting Player Info

Often times, you’ll find it necessary to get info from the player. This can be anything from the players name, to the amount of a certain item that a player has. Let’s write a command that will output the players name in the chat. Now, you may think that you can just do sender.sendMessage(sender); but it’s actually a bit more complicated. When you send a message to a player, you need to give it a string parameter. The variable sender is not a String object. It is a sender object. Here’s the code we should use.

There are two new lines of code here, so I’ll explain these.

Player player = (Player) sender; – first, we’re creating a variable. If you haven’t already figured it out, variables store information. Our variable name is player, and the type of variable it is, is a Player object. We’re setting that variable to the variable sender, but since sender isn’t a Player object, we need to cast the Player object type to the sender object. Casting turns one variable into another. In our case, we’re turning the sender variable into a Player variable because we already know that sender is a Player (We checked to make sure above).

player.sendMessage(player.getName()) – This is where we send the message to the player. player.getName() is the name of the player.

Notice, if you type player.get you get a list of things for the player. Play around with returning different things. Can you figure out how to return the players health? What about the players gamemode?

Also, remember, if you’re using the code posted above, you’ll have to update your plugin.yml with the new command.

Be the first to comment

Leave a Reply

Your email address will not be published.