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

What's the best way to get to the player from a server script?

With filtering enabled on, what would be the best way to get to the player from the server script? So far when I used this it didn't work

Player = game:GetService("Players").LocalPlayer

Then I tried the old way with .Parent untill I get to the player.I think there're some other ways to get to the player that I'd like to know/remember if anyone can provide those.

3 comments

0

you can't do .LocalPlayer because the script does not know what player you are talking about since it affect ALL clients(players) not just one

0

Then do I have to do it with .Parent? or is there another way?

1

If the script is a child of the player's character in some way, then you can do GetPlayerFromCharacter.

3 answers

✓ Accepted answer

You would have to use a functions parameters to define a player, some kind of even must be triggered by one player to the server to be able to get the player. Examples of this:

game.Players.PlayerAdded:Connect(function(player)
	--code
end)

Part.Touched:Connect(function(player) --player is the player who touched the part
	--code
end)

Part.ClickDetector.MouseClick:Connect(function(player)
	--code
end)

--ect...
--FE:
--In local script:
local RemoteEvent = game:GetService("ReplicatedStorage"):WaitForChild("RemoteEvent")

screengui.button.MouseButton1Click:Connect(function(player)
	RemoteEvent:FireServer(x) --x is defaulted to the second parameter when sent to server
end)

--In Server Script

local RemoteEvent = game:GetService("ReplicatedStorage"):WaitForChild("RemoteEvent")

RemoteEvent.OnServerEvent:Connect(function(player, x) --Player is by defaul the first parameter, so x will become second parameter
	print(player.Name .. "Has pressed a button!")
end)

I hope this helped!
Comment if you need any help and if it work accept :D

2 comments

1

well actually with the .Touched event, you have to use :GetPlayerFromCharacter(part.Parent). "part" being the parameter

0

yep

The first parameter every function returns is the player.

So,

function FindPlayer(player)

end

Really the only way is to use function parameters, when the object is fired, it will also define the Player or Character that fired it.

game:GetService("Players").PlayerAdded:connect(function(player) -- returns player
	player.CharacterAdded:connect(function() -- returns character from player

This can be used with really any user triggers functions like a TouchedEvent

script.Parent.Touched:connect(function(whattouched) -- returns whatever touched the part
if whattouched.Parent:FindFirstChild("Humanoid") then -- continues by getting character
print(game.Players:GetPlayerFromCharacter(whattouched.Parent.Name)) -- prints player name from character

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