Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Check if a part touched a part?

Asked by 5 years ago

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?

0
the touched event comes with an "otherPart" parameter which is the part it is touching. GoldAngelInDisguise 297 — 5y
0
How would I use this then DanielDeJong3 158 — 5y

2 answers

Log in to vote
0
Answered by 5 years ago
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)
0
Change touch_part to the part that you want to connect the Touched event to. Accept if this helped you thanks Cronizete 11 — 5y
Ad
Log in to vote
0
Answered by
BenSBk 781 Moderation Voter
5 years ago
Edited 5 years ago

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.
0
Didn't work DanielDeJong3 158 — 5y
0
You obviously have to adapt the code to suit your problem BenSBk 781 — 5y
0
how the hell would I assign a basepart when there's no frikin explenation anywhere on the web DanielDeJong3 158 — 5y
0
base_part is just any BasePart (a MeshPart, Part, etc.) BenSBk 781 — 5y

Answer this question