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
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
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)
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.