Hello everyone, quick question.
How do I get a player object from a .Touched event?
Hello everyone, quick question.
How do I get a player object from a .Touched event?
Part.Touched:Connect(function(Object)
if Object.Parent:FindFirstChild("Humanoid") then
print("Character Detected")
end
end)
or are you referring to something like game.Players.LocalPlayer?
Referring to an actual Player object, not a Character object
Part.Touched:Connect(function(Object)
if Object.Parent:FindFirstChild("Humanoid") then
local Player = game.Players[Object.Parent.Name]
end
end)
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.
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)
part.Touched:Connect(function(hit)
local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
if player then
-- do stuff
end
end)
script.Parent.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
end
end)
local Players = game:GetService("Players")
script.Parent.Touched:Connect(function(Part)
local Char = Part:FindFirstAncestorOfClass("Model")
if Char then
local Player = Players:GetPlayerFromCharacter(Char)
if Player then
-- DoStuffWith(Player)
end
end
end)
hmm?
local Players = game:GetService("Players")
local part = script.Parent
local function checkHit(hit)
local model = hit:FindFirstAncestorWhichIsA("Model")
if model then
local humanoid = model:FindFirstChild("Humanoid")
if humanoid then
return Players:GetPlayerFromCharacter(model)
end
end
end
local function touchPart(hit)
local player = checkHit(hit)
if player then
-- do stuff here
end
end
part.Touched:Connect(touchPart)
--To get a real player
script.Parent.Touched:Connect(function(Hit)
if game.Players:GetPlayerFromCharacter(Hit.Parent) and hit.Parent:FindFirstChild("Humanoid")then
Local Character = hit.Parent
Local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
end
end)
--To get an NonPlayer
script.Parent.Touched:Connect(function(Hit)
if hit.Parent:FindFirstChild("Humanoid")then
Local Character = hit.Parent
end
end)
Part.Touched:Connect(function(player)
if(game.Players:GetPlayerFromCharacter(player.Parent)) then -- Check if the part is a human