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?
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)
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.