GetTouchingParts firing on a canCollide off object

So I don’t need any support really but I want some one to help me understand this. I have a part with CanCollide off and I have a GetTouchingParts function and it doesn’t detect it but when I add a .touched event to that part it starts detecting it even though it has CanCollide off. The code:

local temp = -15
local laserCount = 0
local temperatureGain = 1
local timeWait = 1

script.Parent.Touched:Connect(function(obj)
	if obj.Parent:FindFirstChild("Humanoid") then
		obj.Parent.Humanoid.Health = 0
	end
end)

while wait(timeWait) do
	laserCount = 0
	local touchingParts = script.Parent:GetTouchingParts()
	for i,v in pairs(touchingParts) do
		print(v.Name)
		if v.Name == "Laser" then
			laserCount = laserCount + 1
		end
	end
	temp = temp + (temperatureGain * laserCount)
	print(temp)
	print(laserCount)
end

This prints the name of the laser every time but when I remove the .Touched function it doesn’t print anything. I want this to not detect the laser when it has CanCollide off. Any suggestions are greatly appreciated.

So here is what the API Reference page says about GetTouchingParts()

Returns a table of all parts that are physically interacting with this part. If the part itself has CanCollide set to false, then this function will return an empty table UNLESS it has a TouchInterest (AKA: Something is connected to its Touched event). Parts that are adjacent but not intersecting are not considered touching.

So if the Touched function gets called, it adds the TouchInterest instance, which would explain why it detects it.

Connecting a Touched event to a base part will insert a TouchInterest object to the base part, as the Touched event relies on it

Quoted from the developer hub page documenting GetTouchingParts:

Returns a table of all parts that are physically interacting with this part. If the part itself has CanCollide set to false, then this function will return an empty table UNLESS it has a TouchInterest (AKA: Something is connected to its Touched event). Parts that are adjacent but not intersecting are not considered touching.

If you want it to not detect any parts if CanCollide is off, simply add an if statement (however I used an implicit ternary operator):

while true do
	laserCount = 0
	local touchingParts = script.Parent.CanCollide and script.Parent:GetTouchingParts() or {}
	for i,v in pairs(touchingParts) do
		print(v.Name)
		if v.Name == "Laser" then
			laserCount = laserCount + 1
		end
	end
	temp = temp + (temperatureGain * laserCount)
	print(temp)
	print(laserCount)
    wait(waitTime)
end

Also, don’t use wait as a condition for a while loop

1 Like