How to find the player in workspace with script.Parent.Touched:Connect(function()

Well, I knew how to do it but there is a problem with this and it is that if it finds the name of the player if you touch the part, but the accessories of the character also detect them and I really do not know what the problem is.

local function Lumber(hit)
	local Owner = script.Parent.Parent:FindFirstChild("Owner")
	
	if Owner.Value == "N/A" then
		local Player = hit.Parent
		print(Player)
	end
end

script.Parent.Touched:Connect(Lumber)

Red Panda is the accessory, that’s a problem because I need something for an owners system. and NUTRICORP is the player

Script - Roblox Studio 31_07_2021 01_37_49 a. m. (3)_LI

I tend to use the following:

local function Lumber(hit)
	local Humanoid = obj.Parent:FindFirstChild("Humanoid")
	local character
	if Humanoid then
		character = obj.Parent
	end
--	print("Char: ", character.Name)
	if character then --If a model was found
		local player = Players:GetPlayerFromCharacter(character) --Get the player from character model.
		--print("SELL: ", player.Name, " ", Players.LocalPlayer.Name)
		if player then
			if player.Name == Players.LocalPlayer.Name then
				--Now you have the correct player object, and you can do stuff
				
			end
		end
	end
end
1 Like

This would probably be the simpler approach

local Players = game:GetService("Players")

local function Lumber(hit)
	local character = hit:FindFirstAncestorOfClass("Model")
	local player = Players:GetPlayerFromCharacter(character)
	if not player then
		return
	end
	--Stuff to do on player or on their character
end

FindFirstAncestorOfClass would find the first ancestor of the hit part that is a model or nil if it couldn’t find any, this would make it still get the character even if an accessory touched the part, then you give GetPlayerFromCharacter that character, no need to check if the character exists because it’ll s till accept nil and will thus return nil, only time you need to check is to see if it found a player from that character, then afterwards is the code. The way you have it feels a bit too complicated.

Also, not sure why you have if player.Name == Players.LocalPlayer.Name then when @OP is using a server script and not a localscript

1 Like