How to get player from .touched event

I want to get the player when they touch a gem. So I know I could just do hit.Parent.Name to get the players name but that would not work if they touched it with any accessories like hair. So how would I accurately get the player?

Code:

for _, Gem in pairs(Gems) do
		Gem.Touched:Connect(function(hit)

		end)
	end
1 Like
function GetPlayer(hit)
if game.Players:FindFirstChild(hit.Parent.Name) then 
return game.Players:FindFirstChild(hit.Parent.Name)
elseif game.Players:FindFirstChild(hit.Parent.Parent.Name) then 
return game.Players:FindFirstChild(hit.Parent.Parent.Name)
else 
return false
end
1 Like
for _, Gem in pairs(Gems) do
		Gem.Touched:Connect(function(hit)
			local outside = hit.parent
			print(outside.name)
		end)
	end
1 Like

With that how would I then make a variable for that player

local plr = GetPlayer(hit)
if plr == false then return end

1 Like

this hurts me physically and mentally :sad:

1 Like

I’d recommend making use of the built-in Instance:FindFirstAncestorOfClass() and Players:GetPlayerFromCharacter() methods for the following reasons:

  • The :FindFirstAncestorOfClass() method can be used first to retrieve the Character model, even if BaseParts within the Character’s Accessories activated the Touched event (which is the functionality that you described you were looking for in the original post).

  • The Players:GetPlayerFromCharacter() method can then be used on the Character model to immediately retrieve the player Instance.

Example:

local Players = game:GetService("Players")

workspace.examplePart.Touched:Connect(function(hit)
    local possibleCharacterModel = hit:FindFirstAncestorOfClass("Model")
    local Player = Players:GetPlayerFromCharacter(possibleCharacterModel)

    if possibleCharacterModel and Player then -- Checks if an Instance with the "Model" ClassName was found and if the :GetPlayerFromCharacter() method returned the Player Instance from that
        print("A player's Character touched the 'examplePart' in the Workspace!")
    end
end)
2 Likes
local players = game:GetService("Players")

for _, Gem in pairs(Gems) do
	Gem.Touched:Connect(function(hit)
		local hitModel = hit:FindFirstAncestorOfClass("Model")
		if hitModel then
			local hitPlayer = players:GetPlayerFromCharacter(hitModel)
			if hitPlayer then
				--Do stuff with player.
			end
		end
	end)
end

You should be using the available instance methods for fetching player instances instead of FindFirstChild().

Would also be worth defining your function locally as to integrate it into the local environment.

Part.Touched:Connect(function(hit)
      local player = game.Players:GetPlayerCharacter(hit.Parent)
end)

“GetPlayerFromCharacter” is a useful function that allows you to get the player from the character. Hopefully that helps.

You could change it to “local function”.