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

Check if a part touched a part?

So I was trying to make some sort of thing that'd print something when a specific part is touching the part I tried using this:

function touched()
local parts = script.Parent.Head:GetTouchingParts()
print(script.Parent.Head.Name)

for i,v in pairs(parts) do
	print(v.Name)
if v.Name == "Present" then
print("Yay!")
end
end
end

script.Parent.Head.Touched:Connect(touched)

Without much luck because all this does is check if a person touched it then print the name of whater it touched the part with like, Head Torso Arm etc Any tips on how I could do this?

2 comments

0

the touched event comes with an "otherPart" parameter which is the part it is touching.

0

How would I use this then

2 answers

local touch_part = workspace.Part --// you can change this

touch_part.Touched:connect(function(hit)
	if hit.Name == "Present" then
		print("Yey!") --// you can change this too
	end
end)

1 comment

0

Change touch_part to the part that you want to connect the Touched event to. Accept if this helped you thanks

BasePart.Touched passes one argument to its listeners, the other part that touched the BasePart. You can use this to your advantage:

-- Assume assignment of base_part.
local function on_touched(other_part)
	if other_part.Name == "foo" then
		print("Touched by foo.")
	end
end
base_part.Touched:Connect(on_touched)

Note my localisation of the on_touched function. Using local variables instead of global variables whenever possible is good practice. They help avoid cluttering the global environment with unnecessary names, access to local variables is faster than to global ones, and local variables usually vanish as soon as the block ends, allowing their values to be garbage collected.

######If this helped, please accept the answer.

4 comments

0

Didn't work

0

You obviously have to adapt the code to suit your problem

0

how the hell would I assign a basepart when there's no frikin explenation anywhere on the web

0

base_part is just any BasePart (a MeshPart, Part, etc.)

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