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

How do I reference the player from a server script?

Asked by 6 years ago

So this script works when I test on the client, but not in a server. I know it's because I'm trying to reference the player, but I'm not sure how I should be doing it from a server script.

function teleport()
    local target 
    for i, player in ipairs(game.Players:GetChildren()) do
        if player.Playing.Value == 0 then
            local char = player.Character or player.CharacterAdded:Wait()
            if char.Humanoid.Health ~= 0 and char:FindFirstChild("Choice") then -- "Choice" from vehicle select gui local script
                print("Choice")
                -- ADD CARS HERE. Probably a more efficient way to do this
                if char.Choice.Value == "Car1" then
                    local Car1 = game.ServerStorage.Car1:Clone()
                    Car1.Parent = game.Workspace
                    target = Car1.PrimaryPart.CFrame
                    char.HumanoidRootPart.CFrame = target
                    player.Playing.Value = 1
                end
            else if char.Choice.Value == "Car2" then
                -- etc
                end
            end
        end
    end
end

1 answer

Log in to vote
0
Answered by 6 years ago

In a local script (as you already know) use LocalPlayer local plr = game.Players.LocalPlayer

In a serverscript there are multiple ways

1) Getting all children of 'Players'

for index, plr in pairs(game.Players:GetPlayers()) do
    -- Code
end

2) Using the playeradded event

game.Players.PlayerAdded:Connect(function(plr)

end)

3) Using a local script with remote events to talk with each other

local Event = game:GetService('ReplicatedStorage'):WaitForChild('Event')

Event.OnServerEvent:Connect(function(plr)

end)

4) Getting a random player (using way 1) local player = game.Players:GetPlayers()[math.random(1, #game.Players:GetPlayers())]

If you have any more questions, just ask :)

0
I did 1) in line 3. Must be a different problem? Lord_Pear 6 — 6y
0
Problem is in line 2, local target = -- then nothing, why? or just a bad copy? User#20388 0 — 6y
0
I defined that in line 15 Lord_Pear 6 — 6y
0
Not 15, 12 Lord_Pear 6 — 6y
View all comments (4 more)
0
Never mind. It was an issue with firing the function that stemmed from a different script. Thanks for your help Lord_Pear 6 — 6y
0
Np :) User#20388 0 — 6y
0
Still trying to wrap my head around filtering enabled lol. I keep forgetting about it Lord_Pear 6 — 6y
0
Well, if you have any questions about it, just ask me lol User#20388 0 — 6y
Ad

Answer this question