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

How can I obtain the Player from a Touched function?

Asked by 9 years ago

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!

2
You're suppose to use :GetPlayerFromCharacter alphawolvess 1784 — 9y

1 answer

Log in to vote
1
Answered by
yumtaste 476 Moderation Voter
9 years ago

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

Ad

Answer this question