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 find the player with a part touched ?

So , my question is that i want to find a value who are in the player folder Like : "Game.Players.LocalPlayers.TheValue" But i want to get this value with a touched part . Find The player value when the player hit a part

local PlayersService = game:GetService("Players")

local function onTouch(hit)

if hit.Parent:FindFirstChild('Humanoid') then

local namee = hit.Parent.Name

print(namee)

local lol = game.Players.namee

print(lol)

end

end

script.Parent.Touched:connect(onTouch)

I tried something but i didn't work so if u know help me :c Thx !

2 answers

✓ Accepted answer

Using Players.LocalPlayer will give you a static value of either nil or the clients player, depending on if you're using it serverside or clientside. Using Players.GetPlayerFromCharacter you can get the player based on a character model which in the case of a touching part would be Part.Parent as the touching part of a character model is directly parented to the model itself.

local Players = game:GetService("Players")

local function onTouch(hit) -- hit being the part that touched provided by the event
    local player = Players:GetPlayerFromCharacter(hit.Parent)
    if player then -- all parts that touch might not be from character models (player is nil)
        print(player.Name, "touched")
    end
end

script.Parent.Touched:Connect(onTouch)

If the script is inside a part then... This is the script WITH debounce:

local Players = game:GetService("Players")
local debounce = false

script.Parent.Touched:Connect(function(hit)
local humanoid = hit.Parent:FindFirstChild("Humanoid")
    if humanoid then
      if debounce = false then
      debounce = true
		local player = Players:GetPlayerFromCharacter(hit.Parent)
	    print (player.name)
	    wait(2) -- 2 second debounce
	    debounce = false
	    end
    end
end)

Script with NO debounce

local Players = game:GetService("Players")

script.Parent.Touched:Connect(function(hit)
local humanoid = hit.Parent:FindFirstChild("Humanoid")
    if humanoid then
		local player = Players:GetPlayerFromCharacter(hit.Parent)
	    print (player.name)
    end
end)

I hope this is helpful!

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