Bukkit Coding – (6) Player or Console

Often times, it’ll be necessary for you to identify who typed a specific command. In order to do so, you must first determine if the command is coming from a player, or from the console. Like before, I’ll show you the code and then explain how it works.

There’s only one line of code, so I’ll break it up so it’s easier to understand.

if( – This is just the beginning of an if statement like we saw before.

sender – We used this variable earlier. It’s just the player or console that entered the command.

instanceof – For now, all you have to know is that a variable type will come after instanceof, and a variable will come before it. Instanceof will check to see if the variable before it, is the same variable type as the variable type after it. For example ”This is a string” instanceof String would return true since “This is a string” is a string.

Player – This is the variable type we’re testing. Player variables are added by Bukkit.

In plain english, we’re pretty much testing to see if the person that typed the command, is a Player or not. If it is, it’ll output “Hello World” in chat with green text.

But what if we want to do something different if the person that issued the command is the console? It’s actually pretty easy.

We’ve really only added one new line of code here, so I’ll just explain it.

else{ – This is pretty much saying that if sender instanceof Player is false (if the person running the command is not a player), then it’ll run the code in the body of the else. This is known as an else statement. You’ll often see these with an if statement.

The full code for this example can be found HERE.

Now, go ahead and export this plugin and run it on a test server. You should notice that if you run the command “hello” in-game, you should get “This is a player.” send to you in chat, and if you run the command “hello” in the console, you’ll get “This is the console.”.

Seems pretty easy again, right? Well what if you want to bypass the player check, and just check to see if the person running the command is the console? This is pretty easy.

 

Again, we’ve only changed one line of code, so I’ll just explain this one line.

if(!(sender instanceof Player)){ – An exclamation mark is used to tell the if statement that we’re looking to see if the opposite is true (in other words, we’re checking to see if the if statement is false instead of true).

In plain english, we’re checking to see if the sender is not a player, and running the code in the body of the if statement.

Be the first to comment

Leave a Reply

Your email address will not be published.


*