How to Get Player Through Touched Event: The Tutorial
When a .Touched
event fires, check if the touched object’s parent is a model and that it has a humanoid. Then, you should use Players:GetPlayerFromCharacter()
, inserting the character model into the argument in order to obtain player.
If it’s an NPC, it usually returns nil. Make sure to use an if
statement for that.
Example
local Players = game:GetService("Players")
local TouchPart = workspace["Part"] -- assign a part to it
TouchPart.Touched:Connect(function(touched)
if touched.Parent:IsA("Model") and touched.Parent:FindFirstChild("Humanoid") then
local Player = Players:GetPlayerFromCharacter(touched.Parent)
if Player then
-- do something here
end
end
end)