Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I reference the player from a server script?

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

✓ Accepted answer

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
  1. Using the playeradded event
game.Players.PlayerAdded:Connect(function(plr)

end)
  1. 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)
  1. 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 :)

8 comments

0

I did 1) in line 3. Must be a different problem?

0

Problem is in line 2, local target = -- then nothing, why? or just a bad copy?

0

I defined that in line 15

0

Not 15, 12

0

Never mind. It was an issue with firing the function that stemmed from a different script. Thanks for your help

0

Np :)

0

Still trying to wrap my head around filtering enabled lol. I keep forgetting about it

0

Well, if you have any questions about it, just ask me lol

This discussion is preserved as it was. New answers, comments, and votes are closed.