Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
-3

How do you define player in a server script?

Asked by
Zrxiis 26
7 years ago

How do you define player in a server script.

0
You'll have to define it manually, via a loop/ whatever method to retrieve the player. TheeDeathCaster 2368 — 7y

2 answers

Log in to vote
4
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago
Edited 7 years ago

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?.

Ad
Log in to vote
-3
Answered by 7 years ago

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
0
But what if the "name" value is lower-cased? How will the script know? ;-; TheeDeathCaster 2368 — 7y
0
When is that usually the case? Kampfkarren 215 — 7y

Answer this question