Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can a touched:connect(Hit) function ignore players or certain parts?

Please Help! I'm about to give Up on this. Or How do you Prevent a part from getting Touched in the first place?

local Part = script.Parent

local ignoretable = {"Humanoid"}

Part.Touched:connect(function(hit)
	if hit.ignoretable then
	else
		---- code
	end
end)

2 answers

✓ Accepted answer

If you'd like to ignore players and certain parts then make a folder in workspace called "Ignore" and put them in there.

--Script
local ignore_list = workspace:WaitForChild("Ignore"):GetDescendants()
function touched(hit)
	local ignored
	for i, v in next, game.Players:GetPlayers() do --Gets all players in the session
		for i, x in next, v.Character:GetDescendants() do --Gets all descendants of their characters
			if x:IsA("BasePart") then --If it's a part, then;
				table.insert(ignore_list, x) --Make it ignored
			end
		end
	end
	

	for i, v in next, ignore_list do --Scans the ignore list
		if v == hit then 
			ignored = true --The hit is either a player or an ignored part
			break --breaks the loop since it's an ignored part
		end
	end
	
	if not ignored then
		--code
	end		
end

This code is based off of instances rather than strings, just a heads up!

Something like this if you want to ignore all players:

local Part = script.Parent

Part.Touched:connect(function(hit)
    if not hit.Parent:FindFirstChild("Humanoid") then -- ignores all players
        print("Not a player")
    else
        ---- code
    end
end)

If you want it to ignore certain parts then You can just iterate through all the ignoreParts, and check if it should be ignored or not. Something like this:

local Part = script.Parent

local ignoreTable = {"Part1", "Part2", "Part3"} -- put the part's names here

local function shouldIgnore(part)
    local ignoreable = false
    for _, v in pairs(ignoreTable) do
        if v == part.Name then
            ignoreable = true
        end
    end
    return ignoreable
end

Part.Touched:connect(function(hit)
    if shouldIgnore(hit) then -- ignores all players
        print("Not in ignore list")
    else
        ---- code
    end
end)

Those are two ways of doing them, you get the idea, you can replace the names with objects of actual parts instead if you want.

Hope I helped, please let me know if you have any questions!

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