Java Reference
In-Depth Information
For instance, Minecraft keeps a pile of interesting data and functions related
to each player who's online. Its “recipe” is defined by the class
net.canary-
mod.api.entity.living.humanoid.Player
, which builds objects for an individual
Player
.
Note that before you can use
Player
in your code, you must add an import
statement at the very top of the file—in this case you'd do an
importnet.canary-
mod.api.entity.living.humanoid.Player
.
So how can we get at one of these player objects?
The Minecraft server knows who's online at any point, so we can ask the
server for a list of
Player
objects. Or we can ask for a specific user by name,
and it will give us a single
Player
object. Here's how.
Within a plugin, you can get access to the server using the function named
Canary.getServer()
. That will give you an object representing the server. Once you
have the server object, you can ask it for the player you want. You use
getPlayer
and call it with the name of the player you want.
That sequence of instructions looks like the following. (We're going to look at
this in bits and pieces first, and end up with a complete running example.)
You start off with the imports that define the class recipes you'll be using:
// Up top
import
net.canarymod.Canary;
import
net.canarymod.api.Server;
import
net.canarymod.api.entity.living.humanoid.Player;
Then later, in your plugin code, you can use variables of those types (
Player
and
Server
):
Server myserver = Canary.getServer();
Player fred = myserver.getPlayer(
"fred1024"
);
Assuming that “fred1024” is online at the moment, we now have a variable
named
fred
that represents the
Player
object. If Fred wasn't online, then the
fred
variable would be equal to the special value
null
, which is Java-speak for “there
ain't one”—in other words,
fred
is not set to any object at all.
1
Objects have parts. They contain stuff. An
int
, like 5, is just the number five.
It can't do anything else; it can't store anything else alongside it. It just is
what it is. But objects have functions and variables that you access with a
period (
.
).
1.
If
fred
was null and you tried to execute a function from
fred
, like
fred.isSneaking()
, you'd
get an error and your plugin would crash.