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

How can I obtain the Player from a Touched function?

I know how to find it in a LocalScript, but if I have a ServerScript, how do I find it? I have tried this code, but I think what I find is Workspace.

local part = script.Parent

local event = part:FindFirstChild("RemoteEvent")

part.Touched:connect(function(hit)
	local player = hit.Parent.Parent
	event:FireClient(player, "connect", hit) 
end)

Thank you for any answer!

1 comment

2

You're suppose to use :GetPlayerFromCharacter

1 answer

✓ Accepted answer

You can use GetPlayerFromCharacter, or just go into Players to get the player. Example:

script.Parent.Touched:connect(function(part)
local player = game.Players:GetPlayerFromCharacter(part.Parent.Name) --the reason this works if someone's character touches it is because a child of the character model's parent is the character. like if my character's left leg touches a brick. the left leg's parent would be a model called "yumtaste," and GetPlayerFromCharacter gets the player called "yumtaste"
if player then --sometimes, an NPC or a random brick can touch the brick that is listening for the Touched event. this makes sure that "player" actually exists, because it might not.
print(player.Name.." just touched mah brik! arrests hims nao!!!")
end
end)

You could also do player = game.Players:FindFirstChild(part.Parent.Name) and still get the player. I just go into Players to find the player because it works just as well, and I just historically used it.

If you have any questions, please feel free to comment!

Upvote and accept

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