Getting a target player?

Hi,
Sorry for my newbiness here with this as I am rusty on Programming still after leaving it for a year.
What I’m trying to do just to test things is to get a target player, such as when doing /teleport (teleports yourself to a target player) or just doing sending a default message to a target player. I know that bukkit has Bukkit.getServer().getPlayer(args[0])
I tried something similar which is:
String[] args = arguments.split(" "); Player target = (Player) server.getPlayer(args[0]); (Declared Server server; in one of the first lines)
But I haven’t had much luck, and I’ve tried looking around on the forums and docs and haven’t had much success either with coming up with something for this. I could be completely overlooking something as well.

So yeah, if anyone can help me figure this out I’d greatly appreciate it, even though it is probably quite simple, and apologies if I worded this quite poorly as well I’ll try to word it better if needed and as well as my mediocre programming knowledge and skills at this stage. Thanks again for taking your time to read this as well.

You could use this method

But as you see it returns a Optional. Because the player could be Null.
More info about Optional here:

So in order to get the player you do something like this:

Optional<Player> target = server.getPlayer(args[0])
if (target.isPresent())
   target.get().dostuffwithPlayer()
else
   System.out.println("Player Not found");

Hi,
Thanks so much for your help but it seems that a NullPointerException is still being produced from it, whether it is a flaw in my code I’m not too sure, I can post it for extra reference(I’ll edit in in this reply if need be) and this; Optional<Player> target = server.getPlayer(args[0]); is giving the error (I included what you suggested to do below it as well). Thanks for helping again :slight_smile:

Can you put your code in a gist?

Sure thing(Seem to be having issues embedding I’m so bad :<);

Link: FakeOp · GitHub

You’re not initializing the server field anywhere. Make sure you set it to game.getServer() on a loading event (e.g. ServerStartEvent).
Additionally, you may want to use CommandSpec
https://github.com/SpongePowered/SpongeAPI/blob/master/src/main/java/org/spongepowered/api/util/command/spec/CommandSpec.java
PR description:

I agree with simon. CommandSpec does the argument parsing.

I wrote a little example: How to use Optional<Text> - #5 by boformer

1 Like

After doing what both simon816 and boformer suggested (thanks so much for giving examples by the way) it seems to have worked just fine! Thank you all so much for assisting me with this I greatly appreciate your help and time :smiley: