How do you define player in a server script.
How do you define player in a server script?
2 answers
Which player?
Which one do you want? Games aren't single player -- lots of people can be playing at a time.
Which one do you want to do something to?
You can do something to each player by just iterating over all of them (in no particular order):
for _, player in ipairs(game.Players:GetPlayers()) do
-- <do stuff to each player>
end
You could do something to a particular player, but which one?
Maybe it's the player that touched a part. In that case you'll probably have a limb of the player's character, and you have to work from there to the Player object itself.
You can use game.Players:GetPlayerFromCharacter(characterModel) to turn a model into a player (or nil if it was some other object in your game)
part.Touched:connect(function(touchingPart)
local model = touchingPart.Parent
-- This model might be a player's character. Let's find out:
local player = game.Players:GetPlayerFromCharacter(model)
if player then
-- It was in fact a player (as opposed to some random other object)
-- <DO STUFF TO `player` HERE>
end
end)
There's lots of other ways to find players.
If you're using their name (either from some hard-coded VIP list or from chat) then you can scan through the players and filter:
-- RETURNS a list of players (which may be empty)
function playersByNickname(nick)
local matching = {}
for _, player in ipairs(game.Players:GetPlayers()) do
if player.Name:lower():find(nick:lower()) then
table.insert(matching, player)
end
end
return matching
end
-- for example,
-- kick everyone with "blue" in their name:
for _, player in ipairs(playersByNickName "blue") do
player:Kick()
end
The question is which one do you want?.
You can reference a player within the Players service.
HOWEVER, you shouldn't do game.Players.PlayerName, as this has its downsides. A player with a name of a property in the Players service (there are plenty) will not be taken with this, and can crash scripts.
I would use this function
local function GetPlayerByName(name)
for i,v in pairs(game:GetService("Players"):GetPlayers()) do
if v.Name == name then return v end
end
end
2 comments
But what if the "name" value is lower-cased? How will the script know? ;-;
When is that usually the case?
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
You'll have to define it manually, via a loop/ whatever method to retrieve the player.